How to make an ArrayList read only in Java?


The unmodifiableList() method of the java.util.Collections class accepts an object of the List interface (object of implementing its class) and returns an unmodifiable form of the given object. The user has only read-only access to the obtained list.

Example

Following Java program creates an ArrayList object, adds elements to it, converts it into a read-only List object.

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayListReadOnly {
   public static void main(String[] args) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println(list);
      //Converting the ArrayList to read only list
      List<String> myList = (List<String>) Collections.unmodifiableList(list);
      System.out.println("Array list converted to read only "+list);
   }
}

Output

[JavaFx, Java, WebGL, OpenCV]
Array list converted to read only [JavaFx, Java, WebGL, OpenCV]

Once you have retrieved the read-only view of a List object you cannot modify its contents, i.e. you cannot add or delete elements from it directly or using the Iterator object, if you do so an UnsupportedOperationException will be raised.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArrayListReadOnly {
   public static void main(String[] args) {
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      System.out.println(list);
      //Converting the ArrayList to read only list
      List<String> myList = (List<String>) Collections.unmodifiableList(list);
      myList.add("CoffeeScript");
      System.out.println("Array list converted to read only "+myList);
   }
}

Run time exception

[JavaFx, Java, WebGL, OpenCV]
Exception in thread "main" java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
   at SEPTEMBER.remaining.ArrayListReadOnly.main(ArrayListReadOnly.java:20)

Updated on: 14-Oct-2019

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements