Thursday 14 July 2022

How to get unmodifiable view of a List in Java?

Java Collections.unmodifiableList method return unmodifiable view of the specified list.

 

Signature

public static <T> List<T> unmodifiableList(List<? extends T> list)

 

Example

List<Integer> unmodifiablePrimes = Collections.unmodifiableList(primes);

 

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

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

 

In brief, following operations throw UnsupportedOperationException on unmodifiable list.

a.   set

b.   add

c.    remove

d.   addAll

e.   replaceAll

f.     sort

g.   list iterator remove, set and add methods.

 

Find the below working application.

 

UnmodifiableViewOfAList.java


package com.sample.app.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class UnmodifiableViewOfAList {

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

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

		List<Integer> unmodifiablePrimes = Collections.unmodifiableList(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.set(1, 23);
		} catch (Exception e) {
			System.err.println("\nError while performing set operation : ");
			e.printStackTrace();
		}

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

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

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

		try {
			unmodifiablePrimes.sort((item1, item2) -> item1.compareTo(item2));
		} catch (Exception e) {
			System.err.println("\nError while performing sort 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 list are immutable, unmodifiable list not completely safe, because while list might be unmodifiable, but the elements may be themselves modified.

 

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

List<Employee> unmodifiableEmps = Collections.unmodifiableList(emps);

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

Find the below working application.

 

UnmodifiableViewOfAList1.java

package com.sample.app.collections;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class UnmodifiableViewOfAList1 {

	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) {
		List<Employee> emps = Arrays.asList(new Employee(1, "Ram"), new Employee(2, "Siva"), new Employee(3, "Kiran"));

		List<Employee> unmodifiableEmps = Collections.unmodifiableList(emps);

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

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

	}

}

Output

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






 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment