How to make List, Set and Map Read Only in Java

Making HashSet read-only – We have unmodifiableSet(Set<? extends T> s) static method in Collections class.

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

public class ReadOnlySetExp {
	public static void main(String[] args) {

		// creating object of Set
		Set<String> setObjects = new HashSet();

		// adding couple of elements in ArrayList
		setObjects.add("ram");
		setObjects.add("mohan");
		setObjects.add("sohan");
		setObjects.add("rohan");

		// iterating using for-each loop
		System.out.println("before read only list");
		for (String str : setObjects) {
			System.out.println(str);
		}

		// Let's make setObjects read only
		Set<String> readOnlySetObject = Collections.unmodifiableSet(setObjects);

		// adding element in readOnlyListObject

		readOnlySetObject.add("shyam");
		System.out.println(readOnlySetObject);
	}
}

before read only list
sohan
rohan
mohan
ram
Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at ReadOnlySetExp.main(ReadOnlySetExp.java:28)