
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make an ArrayList Read-Only in Java
A collection is an object that holds a reference to other objects. A Java array list is one of the collections. it is a resizable array and is represented by the class named ArrayList.
This java.util.Collections class provides methods to manipulate the collection objects in Java. We can make an ArrayList read-only using the Collections.unmodifiableList() method.
Need to make a ArrayList Read-Only
Sometimes we may need to make the ArrayList object read-only -
-
To protect data from unnecessary or unwanted changes.
-
It is useful when sharing data between classes where some classes should only view the list, not change it.
Using the unmodifiableCollection() Method
The class named Collections (of the java.util package) provides static methods that are useful to modify all the collection objects.
To prevent modifications to an ArrayList (like adding, removing, or updating elements) and to make it read-only, we need to invoke the method named unmodifiableList(), passing the ArrayList object as an argument.
This method accepts a List object (any object implementing the List interface) as a parameter and returns a read-only form of the given object. The user has only read-only access to the obtained ArrayList.
Example
The following Java program creates an ArrayList object, adds elements to it, and converts it into a read-only List object.
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); } }
Let us compile and run the above program, this will give the following result -
[JavaFx, Java, WebGL, OpenCV] Array list converted to read only [JavaFx, Java, WebGL, OpenCV]
UnsupportedOperationException
Once you retrieve 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
In the following example, we are trying to modify an ArrayList object, which we obtained using the unmodifiableList() method -
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); } }
Let us compile and run the above program, this will give the following result -
[JavaFx, Java, WebGL, OpenCV] ERROR! Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Unknown Source) at SEPTEMBER.remaining.ArrayListReadOnly.main(ArrayListReadOnly.java:20)
Using the List.copyOf() method
In Java 10, there is a simpler and more efficient way to create immutable collections. By using, List.copyOf() method.
While unmodifiableList() allows to read-only view of the original list, the List.copyOf() allows the list itself to be immutable. This method is useful when we need a collection of objects that cannot be changed after it is created.
If you modify the original list using this method, the changes would not reflect in the new list that is the modified list. But if we use the unmodifiableList(), the new list is a view of the original list. This means that if you modify the original list, the changes will be reflected in the new list.
Example
This example compares List.copyOf() and Collections.unmodifiableList() by explaining how both prevent modification. It also shows that unmodifiableList() reflects changes made to the original list, while copyOf() creates a truly independent immutable copy.
import java.util.List; import java.util.Collections; import java.util.ArrayList; public class ListComparison { public static void main(String[] args) { // Create a mutable list (ArrayList) List < String > fruits = new ArrayList < > (); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Using List.copyOf() to create a truly immutable list List < String > immutableFruits = List.copyOf(fruits); // Using Collections.unmodifiableList() to create an unmodifiable list List < String > unmodifiableFruits = Collections.unmodifiableList(fruits); // Try modifying the immutable list (List.copyOf) try { immutableFruits.add("Date"); // This will throw UnsupportedOperationException } catch (UnsupportedOperationException e) { System.out.println("Cannot modify immutableFruits - operation not supported."); } // Try modifying the unmodifiable list (Collections.unmodifiableList) try { unmodifiableFruits.add("Date"); // This will throw UnsupportedOperationException } catch (UnsupportedOperationException e) { System.out.println("Cannot modify unmodifiableFruits - operation not supported."); } // Modify the original list and see if changes are reflected in the unmodifiable list fruits.add("Date"); System.out.println("Original list after modification: " + fruits); System.out.println("Unmodifiable list after original modification: " + unmodifiableFruits); // Will show the updated list } }
Let us compile and run the above program; this will give the following result -
Cannot modify immutableFruits - operation not supported. Cannot modify unmodifiableFruits - operation not supported. Original list after modification: [Apple, Banana, Cherry, Date] Unmodifiable list after original modification: [Apple, Banana, Cherry, Date]