How do you get an Immutable Collection

This functionality is provided by the Collections class, which is a wrapper implementation using the decorator design pattern.

public class ReadOnlyExample {

public static void main(String args[ ]) {

Set<string> set = new HashSet<string>( );

set.add(“Java”);

set.add(“JEE”);

set.add(“Spring”);

set.add(“Hibernate”);

set = Collections.unmodifiableSet(set);

set.add(“Ajax”);                                           // not allowed.

}

}

In Java, to create an immutable collection, you typically use the Collections.unmodifiableXXX methods, where XXX is the type of collection you want to make immutable. Here are examples for different types of collections:

  1. Immutable List:
    java
    List<String> originalList = new ArrayList<>();
    // Add elements to originalList
    List<String> immutableList = Collections.unmodifiableList(originalList);
  2. Immutable Set:
    java
    Set<Integer> originalSet = new HashSet<>();
    // Add elements to originalSet
    Set<Integer> immutableSet = Collections.unmodifiableSet(originalSet);
  3. Immutable Map:
    java
    Map<String, Integer> originalMap = new HashMap<>();
    // Put entries into originalMap
    Map<String, Integer> immutableMap = Collections.unmodifiableMap(originalMap);

Keep in mind that while the collection itself becomes immutable, the elements within the collection may still be mutable if they are objects. So, if you have mutable objects in your collection, modifying those objects will still impact the perceived immutability of the collection.