How to initialize a static Map in Java? Best practices and examples
Hello everyone! I'm new to Java and I have a problem. I need to create a static Map that will store some constant values (for example, mapping country codes to their names). I know I can do it like this:
```java
public class MyClass {
public static final Map countryCodes = new HashMap<>();
static {
countryCodes.put("US", "United States");
countryCodes.put("RU", "Russia");
countryCodes.put("DE", "Germany");
}
}
```
But it seems to me that this is not the most elegant way. First, the Map is not immutable — someone could accidentally change its contents. Second, I've seen that in some projects they use double brace initialization, but with