Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In Java there are unmodifiable maps. These are maps which are wrappers over a modifiable map. With these, if a change is made on the modifiable map then it is reflected in the unmodifiable map. 

Code Block
languagejava
themeConfluence
titleJava UnmodifiableMap Example
Map<String, String> mutableMap = new HashMap<>();

Map<String, String> unmodifiableMap = Collections.unmodifiableMap(mutableMap);

Guava's ImmutableMap, on the other hand, contains its own private data and doesn't allow modification to it. Therefore, the data cannot change in any way once an instance of the Immutable Map is created.

...

In Java 9, Map.of and Set.of were introduced. These are static factory methods which take values on the fly and return Unmodifiable map/set which contain those values. These unmodifiable map/set are immutable as they do not have a mutable map/set which can be accessed to modify the values within the map/set. Limitations to Map.of/Set.of is that they take upto 10 key value pairs for maps and 10 values for sets.

Code Block
languagejava
themeConfluence
titleJava Map.of Example
Map<String, String> immutableMap = Map.of("A", "Apple", "B", "Ball", "C", "Car")

...