How to make an ArrayList read only in Java
Given an ArrayList, the task is to make this ArrayList read-only in Java.
Examples:
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.
Syntax:
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 list.add('X'); list.add('Y'); list.add('Z'); // printing the list System.out.println("Initial list: " + list); // getting readonly list // using unmodifiableList() method List<Character> immutablelist = Collections .unmodifiableList(list); // printing the list System.out.println("ReadOnly ArrayList: " + immutablelist); // Adding element to new Collection System.out.println("\nTrying to modify" + " the ReadOnly ArrayList."); immutablelist.add('A'); } catch (UnsupportedOperationException e) { System.out.println("Exception thrown : " + e); } } } |
chevron_right
filter_none
Output:
Initial list: [X, Y, Z] ReadOnly ArrayList: [X, Y, Z] Trying to modify the ReadOnly ArrayList. Exception thrown : java.lang.UnsupportedOperationException
Recommended Posts:
- ArrayList of ArrayList in Java
- Java.util.ArrayList.addall() method in Java
- How to read a Matrix from user in Java?
- How to Read and Print an Integer value in Java
- ArrayList in Java
- Arraylist.contains() in Java
- Java.util.Arraylist.indexOf() in Java
- Java.util.ArrayList.add() Method in Java
- PushbackReader read() method in Java with Examples
- Image Processing in Java | Set 1 (Read and Write)
- StringReader read() method in Java with Examples
- ObjectInputStream read() method in Java with examples
- CharArrayReader read() method in Java with Examples
- CharBuffer read() methods in Java with Examples
- Reader read() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



