Given an ArrayList, the task is to make this ArrayList read-only in Java.
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.
readOnlyArrayList = Collections.unmodifiableList(ArrayList);
Below is the implementation of the above approach:
Initial list: [X, Y, Z] ReadOnly ArrayList: [X, Y, Z] Trying to modify the ReadOnly ArrayList. Exception thrown : java.lang.UnsupportedOperationException
- ArrayList of ArrayList in Java
- Java.util.ArrayList.addall() method in Java
- Java.util.Arraylist.indexOf() in Java
- Java.util.ArrayList.add() Method in Java
- ArrayList in Java
- Arraylist.contains() in Java
- Initialize an ArrayList in Java
- Arraylist lastIndexOf() in Java with example
- ArrayList isEmpty() in Java with example
- ArrayList trimToSize() in Java with example
- ArrayList vs. HashMap in Java
- ArrayList vs LinkedList in Java
- Synchronization of ArrayList in Java
- Vector vs ArrayList in Java
- Array vs ArrayList in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.