Home >Java >javaTutorial >How to Initialize Static Maps in Java: Static Block vs. Anonymous Subclass?
Initialising Static Maps in Java
In Java, static maps can be initialised using two primary methods:
1. Static Initialiser
This method involves using a static block within the class declaration to initialise the map. An example of this is shown in the provided code sample:
private static final Map<Integer, String> myMap = new HashMap<>(); static { myMap.put(1, "one"); myMap.put(2, "two"); }
Advantages:
Disadvantages:
2. Instance Initialiser (Anonymous Subclass)
This method uses an anonymous subclass to initialise the map. It's written as an instance initialiser but serves the same purpose as static initialisation:
private static final Map<Integer, String> myMap2 = new HashMap<>(){ { put(1, "one"); put(2, "two"); } };
Advantages:
Disadvantages:
Alternatives:
The above is the detailed content of How to Initialize Static Maps in Java: Static Block vs. Anonymous Subclass?. For more information, please follow other related articles on the PHP Chinese website!