How to initialize a static Map in Java? (with examples)
Hello everyone! I'm new to Java and I'm having trouble initializing a static Map. I need to create a constant map (for example, mapping country codes to their names) that will be accessible from anywhere in the program without creating a class instance.
I tried doing this:
```java
public class CountryCodes {
public static final Map codes = new HashMap<>();
codes.put("RU", "Россия");
codes.put("US", "США");
codes.put("DE", "Германия");
}
```
But the compiler gives an error: "Illegal static declaration" or "Cannot resolve symbol 'codes'". I understand that code outside methods doesn't execute, but how do I properly fill the Map? In Python I would just write a dictionary in the class body, but in Java it's more complicated.
I've read about static initialization blocks.
No answers yet.
Log in to leave an answer