English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to create immutable collections in Java

You can define immutable objects whenever you need to create objects that cannot be changed after initialization. There are no specific rules for creating immutable objects; the idea is to restrict access to class fields after initialization.

Set is an interface in the collection framework that does not allow duplicate values.

When creating an immutable collection, you need to keep the following points in mind:

  • We should not be able to add or delete elements from it.

  • We should not be able to add null values to immutable collections.

  • Once an immutable collection is created, you cannot add or delete objects from it, but you can modify the objects stored within it.

Using Java9Of() method

Java9The of() method accepts an element list, creates, and returns an immutable collection of the given elements. Using this method, you can create immutable collections 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);
   }
}

Use the unmodifiableSet() method

This method accepts a collection object as a parameter and returns its unmodifiable form, i.e., the immutable form.

Call this method by passing the required object and getting its immutable form.

Example

In the following Java program, we create a HashSet object and use the unmodifiableSet() method to convert it to an immutable object, and then try to add elements to it.

Since we have set it to 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>();
      //Fill the HashSet
      hashSet.add(1124);
      hashSet.add(3654);
      hashSet.add(7854);
      hashSet.add(9945);
      System.out.println(hashSet);
      //Convert the set object to an immutable object
      Set immutable = Collections.unmodifiableSet(hashSet);
      immutable.add(4466);
   }
}

Output Result

[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)