Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to make an ArrayList read only in Java

  • Difficulty Level : Easy
  • Last Updated : 11 Dec, 2018

Given an ArrayList, the task is to make this ArrayList read-only in Java.


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Input: ArrayList: [1, 2, 3, 4, 5]
Output: Read-only ArrayList: [1, 2, 3, 4, 5] 

Input: ArrayList: [geeks, for, geeks]
Output: Read-only ArrayList: [geeks, for, geeks]

An ArrayList can be made read-only easily with the help of Collections.unmodifiableList() method. This method takes the modifiable ArrayList as a parameter and returns the read-only unmodifiable view of this ArrayList.


readOnlyArrayList = Collections.unmodifiableList(ArrayList);

Below is the implementation of the above approach:

// Java program to demonstrate
// unmodifiableList() method
import java.util.*;
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
        try {
            // creating object of ArrayList<Character>
            List<Character> list = new ArrayList<Character>();
            // populate the list
            // printing the list
            System.out.println("Initial list: "
                               + list);
            // getting readonly list
            // using unmodifiableList() method
                immutablelist = Collections
            // printing the list
            System.out.println("ReadOnly ArrayList: "
                               + immutablelist);
            // Adding element to new Collection
            System.out.println("\nTrying to modify"
                               + " the ReadOnly ArrayList.");
        catch (UnsupportedOperationException e) {
            System.out.println("Exception thrown : " + e);
Initial list: [X, Y, Z]
ReadOnly ArrayList: [X, Y, Z]

Trying to modify the ReadOnly ArrayList.
Exception thrown : java.lang.UnsupportedOperationException

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!