Friday 15 July 2022

How to get unmodifiable view of a Set in Java?

Java Collections.unmodifiableSet method return unmodifiable view of the specified set.

 

Signature

public static <T> Set<T> unmodifiableSet(Set<? extends T> s)

 

What will happen when I try to modify the unmodifiable set?

Any attempt to modify the unmodifiable set, whether direct or via its iterator, result in an UnsupportedOperationException.

 

In brief, following operations throw UnsupportedOperationException on unmodifiable list.

 

a.   add

b.   remove

c.    addAll

d.   removeAll

e.   retainAll

f.     clear

g.   removeIf

h.   set iterator remove, set and add methods.

 

Find the below working application.

 

UnmodifiableSetDemo.java

package com.sample.app.collections;

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

public class UnmodifiableSetDemo {

	public static void main(String[] args) {
		Set<Integer> primes = new HashSet<>();

		primes.add(2);
		primes.add(3);
		primes.add(5);
		primes.add(7);

		Set<Integer> unmodifiablePrimes = Collections.unmodifiableSet(primes);

		System.out.println("items of unmodifiablePrimes : " + unmodifiablePrimes);

		try {
			unmodifiablePrimes.add(11);
		} catch (Exception e) {
			System.err.println("\nError while performing add operation : ");
			e.printStackTrace();
		}

		try {
			unmodifiablePrimes.remove(1);
		} catch (Exception e) {
			System.err.println("\nError while performing remove operation : ");
			e.printStackTrace();
		}

		try {
			unmodifiablePrimes.addAll(Set.of(11, 13));
		} catch (Exception e) {
			System.err.println("\nError while performing addAll operation : ");
			e.printStackTrace();
		}

		try {
			unmodifiablePrimes.removeAll(Set.of(2, 3));
		} catch (Exception e) {
			System.err.println("\nError while performing removeAll operation : ");
			e.printStackTrace();
		}

		try {
			unmodifiablePrimes.retainAll(Set.of(2, 5, 11));
		} catch (Exception e) {
			System.err.println("\nError while performing retainAll operation : ");
			e.printStackTrace();
		}

		try {
			unmodifiablePrimes.clear();
		} catch (Exception e) {
			System.err.println("\nError while performing clear operation : ");
			e.printStackTrace();
		}

		try {
			unmodifiablePrimes.removeIf(num -> num > 5);
		} catch (Exception e) {
			System.err.println("\nError while performing removeIf operation : ");
			e.printStackTrace();
		}

		try {
			Iterator<Integer> iter = unmodifiablePrimes.iterator();
			iter.remove();

		} catch (Exception e) {
			System.err.println("\nError while performing remove operation using iterator : ");
			e.printStackTrace();
		}

	}
}

Output



Note

Unless all the elements in the set are immutable, unmodifiable set not completely safe, because while set might be unmodifiable, but the elements may be themselves modified.

 

For example, if Employee class is mutable, below snippet transform employee names to uppercase.

Set<Employee> unmodifiableEmps = Collections.unmodifiableSet(emps);

unmodifiableEmps.forEach(emp -> {
	emp.name = emp.name.toUpperCase();
});

 

Find the below working application.

 

UnmodifiableViewOfASet1.java

 

package com.sample.app.collections;

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

public class UnmodifiableViewOfASet1 {
	private static class Employee {
		private Integer id;
		private String name;

		public Employee(Integer id, String name) {
			this.id = id;
			this.name = name;
		}

		@Override
		public String toString() {
			return "Employee [id=" + id + ", name=" + name + "]";
		}

	}

	public static void main(String[] args) {
		Set<Employee> emps = Set.of(new Employee(1, "Ram"), new Employee(2, "Siva"), new Employee(3, "Kiran"));

		Set<Employee> unmodifiableEmps = Collections.unmodifiableSet(emps);

		unmodifiableEmps.forEach(emp -> {
			emp.name = emp.name.toUpperCase();
		});

		unmodifiableEmps.forEach(System.out::println);

	}
}

Output

Employee [id=1, name=RAM]
Employee [id=3, name=KIRAN]
Employee [id=2, name=SIVA]

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment