Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialise a static Map?

How would you initialise a static 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<Integer, String> myMap = new HashMap<>();     static {         myMap.put(1, "one");         myMap.put(2, "two");     }      private static final Map<Integer, String> myMap2 = new HashMap<>(){         {             put(1, "one");             put(2, "two");         }     }; } 
like image 824
dogbane Avatar asked Feb 03 '09 15:02

dogbane


People also ask

How do you initialize a map in Java when declaring?

We use a simple utility class to initialize Maps in a fluent way: Map<String, String> map = MapInit . init("key1", "value1") . put("key2", "value2") .

What is static map in Java?

In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.

How do you initialize a zero map?

std::cout << registers["Plop"] << std::endl; // prints 0. This works because even though registers is empty. The operator [] will insert the key into the map and define its value as the default for the type (in this case integers are zero).


1 Answers

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:

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);     } } 
like image 72
6 revs, 5 users 85% Avatar answered Sep 21 '22 22:09

6 revs, 5 users 85%