Java – How to make a HashSet read-only or unmodifiable ?

In this article, we will discuss how to convert a modifiable HashSet into an unmodifiable HashSet using Collections.unmodifiableSet(); method

1. Convert HashSet to Read-only:

  • HashSet is an implementation-class of Set interface which grows/shrink in size dynamically whenever elements is
    • added to HashSet using add() method
    • deleted from existing HashSet using remove() method
  • For some business purpose/requirement, HashSet needs to be made read-only or immutable or unmodifiable
  • To achieve this, use one of the utility method called unmodifiableSet() from Collections class
  • Syntax : Collections.unmodifiableSet(modifiableSet); i.e.; pass modifiable set as input-argument
  • Trying to add/remove/modify an unmodifiable Set throws UnsupportedOperationException as shown in the below example
  • Note: however, adding/deleting elements in the original HashSet is still possible

ConvertHashSetToReadOnly.java

package net.bench.resources.unmodifiable.collection;

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

public class ConvertHashSetToReadOnly {

	public static void main(String[] args) {

		// 1. Set of String
		Set<String> hSet = new HashSet<>();


		// 1.1 add names
		hSet.add("Woman");
		hSet.add("Batman");
		hSet.add("Superman");
		hSet.add("Spiderman");
		hSet.add("Human");


		// 1.2 iterating/printing original Set
		System.out.println("1. Orginal Set : \n");
		hSet.forEach(System.out::println);


		// 2. convert modifiable set to immutable set
		Set<String> unmodifiableSet = Collections
				.unmodifiableSet(hSet);


		// 2.1 iterating/printing original set
		System.out.println("\n\n2. Read-only set : \n");
		unmodifiableSet.forEach(System.out::println);


		// 3. trying to modify unmodifiable set
		System.out.println("\n\n3. Trying to modify unmodifiable set : \n");
		try {
			unmodifiableSet.add("Newman");
		}
		catch(UnsupportedOperationException usopex) {
			System.out.println("In Exception block : ");
			usopex.printStackTrace();
		}
	}
}

Output:

1. Orginal Set : 

Human
Superman
Batman
Woman
Spiderman


2. Read-only set : 

Human
Superman
Batman
Woman
Spiderman


3. Trying to modify unmodifiable set : 

In Exception block : 
java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
	at net.bench.resources.unmodifiable.collection.ConvertHashSetToReadOnly
.main(ConvertHashSetToReadOnly.java:41)

Related Articles:

References :

Happy Coding !!
Happy Learning !!

Java - How to make a HashMap read-only or unmodifiable ?
Java - How to make an ArrayList read-only or unmodifiable ?