Home > Java > javaTutorial > How to Initialize Static Maps in Java: Static Block vs. Anonymous Subclass?

How to Initialize Static Maps in Java: Static Block vs. Anonymous Subclass?

Patricia Arquette
Release: 2024-12-03 20:21:16
Original
634 people have browsed it

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");
}
Copy after login

Advantages:

  • Simple and straightforward
  • Guarantees initialisation upon class loading

Disadvantages:

  • May not be suitable for complex initialisation logic

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");
    }
};
Copy after login

Advantages:

  • Allows for more complex initialisation logic
  • Creates an immutable map

Disadvantages:

  • Requires creating an anonymous subclass
  • May not be supported in all scenarios (e.g., when the class is final)

Alternatives:

  • Immutable Static Maps: By initialising a map using a static block and then calling Collections.unmodifiableMap(map), you can create an immutable static map.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template