How to make an ArrayList read only in Java

By Preeti Jain Last updated : February 05, 2024

Read Only ArrayList

If we make ArrayList as Read-Only i.e. we can only read ArrayList and we cannot perform other operations on ArrayList like delete, replace, add by using remove(), set(), add() methods, in read-only mode or in other words we cannot perform any modification in the ArrayList during Read-Only mode.

Problem statement

Given an ArrayList, write a Java program to make the given ArrayList read-only.

Making an ArrayList Read-Only

To make an ArrayList read-only, we use unmodifiableCollection() method of the Collections class.

The unmodifiableCollection() Method

  • unmodifiableCollection() method is available in java.util package.
  • unmodifiableCollection() method is used to make java collections (ArrayList) read-only.
  • unmodifiableCollection() method is used to returns the same ArrayList as we input (i.e. unmodifiable view).

Syntax

public static Collection unmodifiableCollection(Collection co){
}

Parameter(s)

co – represents the ArrayList collection object for which an unmodifiable view is to be returned.

Return value

The return type of this method is Collection, it returns an unmodifiable view of the collection.

Java program to make an ArrayList read only

// Java program to demonstrate the example of 
// Java ArrayList make Read-Only by using 
// unmodifiableCollection() method of Collections class

import java.util.*;

public class ArrayListMakeReadOnly {
    public static void main(String[] args) {
        // ArrayList Declaration
        Collection arr_list = new ArrayList();

        // By using add() method to add few elements in 
        // ArrayList
        arr_list.add(10);
        arr_list.add(20);
        arr_list.add(30);
        arr_list.add(40);
        arr_list.add(50);

        // Display ArrayList 
        System.out.println("Display ArrayList Elements");
        System.out.println(arr_list);

        System.out.println();


        // By using unmodifiableCollection() method is used to make 
        // ArrayList Read-Only
        Collection al_ro = Collections.unmodifiableCollection(arr_list);

        // We will get an exception if we add element in Read-Only 
        // ArrayList i.e. Below statement is invalid

        // al_ro.add(60); 

        // We will get an exception if we delete element from Read-Only 
        // ArrayList i.e. Below statement is invalid

        // al_ro.remove(1); 

        // We will get an exception if we replace element in Read-Only 
        // ArrayList i.e. Below statement is invalid

        // al_ro.set(2,60); 
    }
}

Output

The output of the above program is:

Display ArrayList Elements
[10, 20, 30, 40, 50]

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.