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
No answers yet.
Log in to leave an answer
Blogs
CI/CD for C# Projects: GitHub Actions from A to Z
Kotlin from Zero to Pro: YouTube Channels and Courses Worth Watching
Security of Go Applications: Top 10 Vulnerabilities in Practice
Microservices in Kotlin: Architecture and Practice from A to Z