Java 9 Dependency Injection
上QQ阅读APP看书,第一时间看更新

Immutable collections with convenient factory methods

Many times we directly add or remove elements from a collection, which is returned from the factory method. This collection is immutable and adding items into these collection gives us an exception called UnSupportedOperationException.

To avoid such situations, we create immutable collection objects by using the collections.unmodifiableXXX() method. These methods are also tedious, such as writing multiple statements for adding individual items and then adding into it immutable List or Set or Map:

Before Java 9, 
List<String> asiaRegion = new ArrayList<String>();
asiaRegion.add("India");
asiaRegion.add("China");
asiaRegion.add("SriLanka");
List<String> unmodifiableAsiaRegionList = Collections.unmodifiableList(asiaRegion);

Java 9 provides convenient immutable factory methods such as List.of(), Set.of() and Map.of() to solve the previously mentioned issue:

After Java 9,
List<String> asiaRegion = List.of("India","China","SriLanka");
Set<Integer> immutableSet = Set.of(10, 15, 20, 25);