Factory method to create Immutable Set in Java SE 9

Java Programming Java8Object Oriented Programming

With Java 9, new factory methods are added to Set interface to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in concise way.

Old way to create collections

Example

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class Tester {
   public static void main(String []args) {

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

      set.add("A");
      set.add("B");
      set.add("C");
      Set<String> readOnlySet = Collections.unmodifiableSet(set);
      System.out.println(readOnlySet);
      try {
         readOnlySet.remove(0);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following output.

[A, B, C]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1058)
at Tester.main(Tester.java:15)

New Methods

With java 9, following methods are added to Set interface along with their overloaded counterparts.

static <E> Set<E> of(); // returns immutable set of zero element
static <E> Set<E> of(E e1); // returns immutable set of one element
static <E> Set<E> of(E e1, E e2); // returns immutable set of two elements
static <E> Set<E> of(E e1, E e2, E e3);
//...
static <E> Set<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10);
static <E> Set<E> of(E... elements);// returns immutable set of arbitrary number of elements.

Points to Note

  • For Set interface, of(...) method is overloaded to have 0 to 10 parameters and one with var args parameter.

  • These methods returns immutable set and elements cannot be added, removed, or replaced. Calling any mutator method will always cause UnsupportedOperationException to be thrown.

New way to create immutable collections

Example

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class Tester {
   public static void main(String []args) {

      Set<String> set = Set.of("A","B","C");
      Set<String> readOnlySet = Collections.unmodifiableSet(set);
      System.out.println(readOnlySet);
      try {
         readOnlySet.remove(0);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following output.

[A, B, C]
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.remove(Collections.java:1058)
at Tester.main(Tester.java:10)
raja
Published on 13-Aug-2018 17:43:02
Advertisements