Before Java 9, Collections.unmodifiableXXX() methods are used to create unmodifiable collections. These methods just behave like wrapper methods which return unmodifiable view or read-only view of the original collection. i.e you can’t perform modifying operations like add, remove, replace, clear etc through the references returned by these wrapper methods. But, you can modify original collection if you have other references to it and those modifications will be reflected in the view returned by these methods.
For example,
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Java9ImmutableCollections
{
public static void main(String[] args)
{
List<String> sportList = new ArrayList<String>();
sportList.add("Hockey");
sportList.add("Cricket");
sportList.add("Tennis");
List<String> unModifiableSportList = Collections.unmodifiableList(sportList);
System.out.println(sportList); //Output : [Hockey, Cricket, Tennis]
System.out.println(unModifiableSportList); //Output : [Hockey, Cricket, Tennis]
unModifiableSportList.add("Wrestling"); //It gives run-time error
sportList.add("Kabaddi"); //It gives no error and will be reflected in unModifiableSportList
System.out.println(sportList); //Output : [Hockey, Cricket, Tennis, Kabaddi]
System.out.println(unModifiableSportList); //Output : [Hockey, Cricket, Tennis, Kabaddi]
}
}
From Java 9, static factory methods are introduced to create immutable collections.
1) Immutable List : List.of()
2) Immutable Set : Set.of()
3) Immutable Map : Map.of() or Map.ofEntries()
Immutable Vs Unmodifiable :
Java 9 Immutable collections and unmodifiable collections returned by the Collections.unmodifiableXXX() wrapper methods are not the same. Unmodifiable collections are just the read-only views of the original collection. You can perform modifying operations on the original collection and those modifications will be reflected in the collections returned by these methods. But, immutable collections returned by Java 9 static factory methods are 100% immutable. You can’t modify them once they are created.
Source : https://javaconceptoftheday.com/java-9-immutable-collections/
newCol = oldCol.add("element")
will produce new collection that is copy of old one with 1 more element, and all references to theoldCol
will still point to the same unchanged old collection. – Elurd