Creating immutable collections before Java 9

/, Java 9/Creating immutable collections before Java 9

Creating immutable Collections before JDK9:

In Java 9 added some factory methods to create immutable collections. See JEP 269: Convenience Factory Methods for Collections. But this guide will explain the techniques to create immutable collections before JDK 9 and flaws in using these techniques. Java 9 how solved these flaws will be explained in next guide.

Case 1:

Creating immutable collections using unmodifiableList(), unmodifiableSet(), unmodifiableMap().

Flaw in Case 1:

In above example you see how to create immutable collections, you can still modify the collection, to see how let’s take set from example, you cannot modify the set using the set2 variable. However, you can still use the set variable to modify theĀ  set and the modifications will be reflected when you read the set using the set2 variable. See below example.

 

Output:

Case 2:

Converting an array to List or Set using Arrays class.

Output:

Case 3:

Using double-brace.

Output:

Case 4:

Using Java 8 Streams.

Output:

Flaws in Case 2, 3, 4:

These techniques case2, case3 and case 4 are also inefficient. For example, just to hold two values in a collection, these techniques create multiple objects backing to hold the values and little verbose also.