Immutable Collections are collections whose contents cannot be changed after creation. In Java, immutable collections were officially introduced in Java 9 using factory methods. They improve safety, readability, and performance in modern Java applications.
List, Set, and Mapof() methodsJava provides static factory methods to create immutable collections. Once created, any attempt to modify them throws UnsupportedOperationException.
List.of(elements)Set.of(elements)Map.of(key, value)
// Creating an immutable List using Java 9+
import java.util.List;
public class ImmutableListDemo {
public static void main(String[] args) {
List names = List.of("Java", "Python", "C++");
System.out.println(names);
}
}
// Attempting to modify immutable collection causes exception
import java.util.List;
public class ModifyImmutable {
public static void main(String[] args) {
List nums = List.of(1, 2, 3);
nums.add(4);
}
}
Try adding elements to see the difference!
The first program prints the list successfully. The second program throws UnsupportedOperationException because immutable collections do not allow modification.
null elements — immutable collections do not allow nullsSet of colorsMap of roll numbers and names