How to create an immutable set in Java?


Whenever you need to create an object which cannot be changed after initialization you can define an immutable object. There are no specific rules to create immutable objects, the idea is to restrict the access of the fields of a class after initialization.

A Set is an interface in collection framework, which does not allow duplicate values.

You need to keep following points in mind while creating an immutable set −

  • We should not be able to add or delete elements from it.
  • we should not be able to add null values to an immutable set.
  • Once you create an immutable set you cannot add or delete objects to it, but you can modify the objects stored it.

Using Of() method of Java9

The of() method of Java9 accepts list of elements, creates and returns an immutable set with the given elements. Using this method, you can create an immutable set in Java.

import java.util.Set;
public class ImmutableSet {
   public static void main(String args[]) {
      Set<Integer> set = Set.of(1458, 5548, 4587);
      System.out.println(set);
   }
}

Using the unmodifiableSet() method

This method accepts a collection object as a parameter and returns an unmodifiable i.ie immutable form of it.

Invoke this method by passing the required object and get its immutable form.

Example

In the following Java program, we have created a HashSet object and converted it into immutable object using the unmodifiableSet() method and tried to add elements to it.

Sinc we made it immutable, a runtime exception will be generated.

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ImmutableSet {
   public static void main(String args[]) {
      Set<Integer> hashSet = new HashSet<Integer>();
      //Populating the HashSet
      hashSet.add(1124);
      hashSet.add(3654);
      hashSet.add(7854);
      hashSet.add(9945);
      System.out.println(hashSet);
      //Converting set object to immutable
      Set immutable = Collections.unmodifiableSet(hashSet);
      immutable.add(4466);
   }
}

Output

[1124, 3654, 9945, 7854]
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
   at MyPackage.ImmutableSet.main(ImmutableSet.java:19)
raja
Published on 06-Aug-2019 12:04:07
Advertisements