You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 10 Next »

CPS-378 - Getting issue details... STATUS

Overview

This document will outline when to use Guava's ImmutableMap/ImmutableSet and Java's Map.of and Set.of.

(Maps and Sets are similar to how they work (in terms of  them being Unmodifiable and Immutable). This document will use maps as an example but the theory is the same for both)

Background

Unmodifiable vs Immutable

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. 

Java 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.

Guava ImmutableMap Example
ImmutableMap<String, String> immutableMap = ImmutableMap.copyOf(mutableMap);
Map.of/Set.of

In Java 9, Map.of and Set.of were introduced. These are static factory methods which take values on the fly and return Unmodifiable maps/sets which contain those values. 

Java Map.of Example
Map<String, String> immutableMap = Map.of("A", "Apple", "B", "Ball", "C", "Car")

Guava also has an ImmutableMap.of/ImmutableSet.of and they work in the same way Java's Map.of/Set.of work.

Implementation

Comments on Unmodifiable vs Immutable

If you want Immutable Map/Set then use Guava's ImmutableMap/ImmutableSet. As Java's Unmodifiable Map/Set are not truly immutable.

When to use Map.of/Set.of

To avoid any sonarcloud complains, use Map.of/Set.of when you want to create an immutable map/set using set of entries that you provide. Even though an unmodifiable map/set is returned, this is still an immutable map/set as there is no mutable map/set, that can be changed.
From CPS codebase, Line 60 of the MutilpartFileUtil.java file found in cps/cps-rest/src/main/java/org/cps/rest/utils/ 

Map.of example from CPS codebase
return Map.of(originalFileName, extractYangResourceContent(multipartFile));

This returns Map<String,String>. This is an immutable map because it does not have a mutable map which can be changed. For example, when an unmodifiable map was created above, a mutable map was supplied to it. If a change was made in the mutable map then the unmodifiable map will also reflect the same change. 


  • No labels