Is there any method to convert a Set to immutable 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.

Method to convert a set to immutable

Yes, Java provides a method named unmodifiableSet() in the Collections class. This method accepts a collection object as a parameter and returns an unmodifiable i.ie immutable form of it.

Example

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

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);
   }
}

Output

[1124, 3654, 9945, 7854]

Once you convert a set object into immutable, if you try to add elements to it generates a run time exception −

Example

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);
      //Adding elements to the immutable set
      immutable.add(4466);
   }
}

Run time exception

[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 07-Aug-2019 15:06:02
Advertisements