How would you initialise a static Map
in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other m
With Eclipse Collections, all of the following will work:
import java.util.Map;
import org.eclipse.collections.api.map.ImmutableMap;
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.impl.factory.Maps;
public class StaticMapsTest
{
private static final Map MAP =
Maps.mutable.with(1, "one", 2, "two");
private static final MutableMap MUTABLE_MAP =
Maps.mutable.with(1, "one", 2, "two");
private static final MutableMap UNMODIFIABLE_MAP =
Maps.mutable.with(1, "one", 2, "two").asUnmodifiable();
private static final MutableMap SYNCHRONIZED_MAP =
Maps.mutable.with(1, "one", 2, "two").asSynchronized();
private static final ImmutableMap IMMUTABLE_MAP =
Maps.mutable.with(1, "one", 2, "two").toImmutable();
private static final ImmutableMap IMMUTABLE_MAP2 =
Maps.immutable.with(1, "one", 2, "two");
}
You can also statically initialize primitive maps with Eclipse Collections.
import org.eclipse.collections.api.map.primitive.ImmutableIntObjectMap;
import org.eclipse.collections.api.map.primitive.MutableIntObjectMap;
import org.eclipse.collections.impl.factory.primitive.IntObjectMaps;
public class StaticPrimitiveMapsTest
{
private static final MutableIntObjectMap MUTABLE_INT_OBJ_MAP =
IntObjectMaps.mutable.empty()
.withKeyValue(1, "one")
.withKeyValue(2, "two");
private static final MutableIntObjectMap UNMODIFIABLE_INT_OBJ_MAP =
IntObjectMaps.mutable.empty()
.withKeyValue(1, "one")
.withKeyValue(2, "two")
.asUnmodifiable();
private static final MutableIntObjectMap SYNCHRONIZED_INT_OBJ_MAP =
IntObjectMaps.mutable.empty()
.withKeyValue(1, "one")
.withKeyValue(2, "two")
.asSynchronized();
private static final ImmutableIntObjectMap IMMUTABLE_INT_OBJ_MAP =
IntObjectMaps.mutable.empty()
.withKeyValue(1, "one")
.withKeyValue(2, "two")
.toImmutable();
private static final ImmutableIntObjectMap IMMUTABLE_INT_OBJ_MAP2 =
IntObjectMaps.immutable.empty()
.newWithKeyValue(1, "one")
.newWithKeyValue(2, "two");
}
Note: I am a committer for Eclipse Collections