Java Program to convert a list to a read-only list


Let’s say the following is our list which isn’t read-only:

List < Integer > list = new ArrayList < Integer > ();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(20);
list.add(40);
list.add(50);

Convert the above list to Read-only:

list = Collections.unmodifiableList(list);

On conversion, now you won’t be add or remove elements from the List. Let us see an example:

The following program will give an error because we first update the list to read only and then try to remove an element from it, which is not possible now. The reason is we have converted the list to readonly and you cannot add or remove element from a read-only list:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<Integer>();
      list.add(10);
      list.add(20);
      list.add(30);
      list.add(40);
      list.add(50);
      list.add(20);
      list.add(40);
      list.add(50);
      System.out.println("List = "+list);
      // converting to read-only
      list = Collections.unmodifiableList(list);
      list.remove(5);
      System.out.println("Updated List: "+list);
   }
}

The following is the output with an error since we are removing an element from a read-only list:

List = [10, 20, 30, 40, 50, 20, 40, 50]
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.base/java.util.Collections$UnmodifiableList.remove(Collections.java:1316)
   at Amit/my.Demo.main(Demo.java:27)

Updated on: 30-Jul-2019

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements