how to create immutable set in java?

The java.util.Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

Collections.unmodifiableSet() method is used to create immutable set in java. It will throws an exception if we try to add, remove or shift elements.

Example

package com.w3spoint;
 
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
 
public class Test {
	public static void main(String args[]){
		//Create HashSet object.
		Set<String> hashSet = new HashSet<String>();
 
		//Add objects to the HashSet.
		hashSet.add("Roxy");
		hashSet.add("Sunil");
		hashSet.add("Sandy");
		hashSet.add("Munish");
		hashSet.add("Pardeep");
 
		//Print the HashSet object.
		System.out.println("HashSet elements:");
		System.out.println(hashSet);
 
		//Immutable set
		Set<String> immutableSet = Collections.unmodifiableSet(hashSet);
 
		//Add element
		immutableSet.add("Naren");
 
	}
}

Output

HashSet elements:
[Munish, Pardeep, Sunil, Roxy, Sandy]
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
	at com.w3spoint.Test.main(Test.java:28)

Java Collections class examples

Content Protection by DMCA.com
Please Share