Java Program to Make the ArrayList Read Only

In the previous article, we have seen Java Program to Reverse ArrayList in Java

In this article we are going to see how we can make an ArrayList read-only in java.

Java Program to Make the ArrayList Read Only

Read only means the arraylist can’t be modified i.e. we can not do any addition, deletion or update of elements using the operations like add( ), remove( ) and set( ) methods on the original list.

Let’s see the program to understand it more clearly.

Java Program to Make the ArrayList Read Only By Using Collections.unmodifiableList()

Approach:

  • Create an arraylist and add some elements to it
  • Use the unmodifiable collection function to create a new array list and pass the array list into it. This is the unmodifiable list and we can’t add or remove elements into it.
  • Display the elements.
  • Now add some elements using add( ) to the unmodifiable list which will give exception.

Program:

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

public class Main
{
    public static void main(String[] args)
    {
        // Creating an empty ArrayList
        ArrayList<String> arr = new ArrayList<String>();
        // Adding elements to the arrayList
        arr.add("One");
        arr.add("Two");
        arr.add("Three");
        // using the nonModifiable list collection
        List<String>unmodifiableList= Collections.unmodifiableList(arr);  
        // Displaying the list
        System.out.println("Arraylist"+unmodifiableList);
        //trying to add elements to the unmodifiable arraylist
        unmodifiableList.add("Zero");
        // Displaying the list which will give exception
        System.out.println("Arraylist modified"+unmodifiableList);
    
    }
}
Output:

Arraylist[One, Two, Three]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
at Main.main(Main.java:18)

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs: