The immutable static factory method Set.of() can provide a convenient way to create unmodifiable sets in Java 9.
An instance of a set created by using the Set.of() method has the following characteristics.
- The set returned by a factory method is conventionally immutable. It means that elements can't be added, removed, or replaced from a Set. Calling of any mutator method on the Set causes UnsupportedOperationException.
- If the contained elements of Set are mutable, it may cause the Set's contents to appear to change.
- An immutable set can be created using static factory methods that don't allow null elements. If we are trying to create with null elements, it throws NullPointerException.
- It rejects duplicate elements at the time of immutable set creation. The duplicate elements passed to a static factory method results in IllegalArgumentException.
- The order of iteration of set elements is unspecified and subject to change.
Syntax
Set.of(E... elements)
Example
import java.util.Set; public class SetOfMethodTest { public static void main(String args[]) { Set<String> names = Set.of("Adithya", "Bhavish", "Chaitanya", "Jai"); System.out.println("Names - " + names); names.add("Raja"); // throws UnsupportedOperationException } }
Output
Names - [Bhavish, Adithya, Jai, Chaitanya] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(Unknown Source) at java.base/java.util.ImmutableCollections$AbstractImmutableSet.add(Unknown Source) at SetOfMethodTest.main(SetOfMethodTest.java:8)