Reputation: 47
I have a non-static class in Java that has a static hashmap field. The hashmap should be initialized with some key-value pairs generated by code. The hashmap is not to be changed after that.
How should this be achieved? Should I just create a static init method and make sure to run this once before using the class, or are there better ways of doing it?
Upvotes: 2
Views: 907
Reputation: 1462
You can easily create immutable maps with Google Guava library:
private static Map<String, String> map = ImmutableMap.of(
"key1", "value1",
"key2", "value2");
If you want to use it for many values then builder()
is provided.
Upvotes: 0
Reputation: 7242
You can use a static initializer block in your class.
e.g.
private static Map<String, String> myMap;
static {
HashMap<String,String> map = new HashMap<String,String>();
map.put("foo","bar");
myMap = Collections.unmodifiableMap(map);
}
Upvotes: 5