snippetjavaCritical
How can I initialise a static Map?
Viewed 0 times
howcaninitialisestaticmap
Problem
How would you initialise a static
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other method?
What are the pros and cons of each?
Here is an example illustrating the two methods:
Map in Java?Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other method?
What are the pros and cons of each?
Here is an example illustrating the two methods:
import java.util.HashMap;
import java.util.Map;
public class Test {
private static final Map myMap = new HashMap<>();
static {
myMap.put(1, "one");
myMap.put(2, "two");
}
private static final Map myMap2 = new HashMap<>(){
{
put(1, "one");
put(2, "two");
}
};
}Solution
The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.
You can create an immutable map using a static initialiser too:
You can create an immutable map using a static initialiser too:
public class Test {
private static final Map myMap;
static {
Map aMap = ....;
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
}Code Snippets
public class Test {
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = ....;
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
}Context
Stack Overflow Q#507602, score: 1202
Revisions (0)
No revisions yet.