by BehindJava

How to make an ArrayList Read Only in Java

Home » java » How to make an ArrayList Read Only in Java

In this tutorial we are going to learn about making an arraylist readonly i.e. unmodifiable.

The read-only means unmodifiable view of Collection in which we can not perform any operation which will change the collection through add(), remove() or set() method. We can obtain read-only collection from the existing collection by calling Collections.unmodifiableCollection() method.

Sample Code Snippet:

public class ReadOnlyArrayList {  
    public static void main(String[] args) {  
        List<String>fruit = new ArrayList<String>();  
  
        fruit.add("Mango");  
        fruit.add("Banana");  
        fruit.add("Apple");  
        fruit.add("Strawberry");  
        fruit.add("Pineapple");  
          
    List<String>unmodifiableList= Collections.unmodifiableList(fruit);       System.out.println(fruit);  
    }  
}  

Since we made this array list as unmodifiable List we cannot add any more elements into the list and if you try to do so, it will cause an exception UnsupportedOperationException.