A read only ArrayList means that no modification operations is allowed to be performed on ArrayList. This list cannot be modified by adding, removing or updating any element in the ArrayList. This is to prevent any modification be done to the ArrayList. The only operations that are allowed to be performed on read only ArrayList are search and read.
Operations Not allowed on Read Only ArrayList:
- Adding of new element using add() method.
- Removing any existing element using remove() method.
- Changing any existing element using set() method.
Operations allowed on Read Only ArrayList:
- Search
- Read
Program to make ArrayList read only
import java.util.*; public class JavaExample { public static void main(String[] args) { //An ArrayList of sports List<String> sports = new ArrayList<String>(); sports.add("basketball"); sports.add("tennis"); sports.add("baseball"); sports.add("golf"); sports.add("volleyball"); //Making ArrayList read only List<String> readOnlyList= Collections.unmodifiableList(sports); //We made the ArrayList "sports" read only //The following add() operation is not allowed on read only lists readOnlyList.add("Cricket"); System.out.println(sports); } }
Output: The programs throws following error because we are trying to add an element to a read only ArrayList. The important note here is that the list returned by the Collections.unmodifiableList()
method is read only, which is readOnlyList
in this example. This doesn’t make the original ArrayList read only which means you can still add, update and remove elements from sports
ArrayList, however you would not be able to do the same in readOnlyList
.
Search and Read operations on read only ArrayList
Let’s see if we can perform search and read operations on the read only list. Here, we are not making any change in the unmodifiable list so the program runs fine.
import java.util.*; public class JavaExample { public static void main(String[] args) { //An ArrayList of sports List<String> sports = new ArrayList<String>(); sports.add("basketball"); //index 0 sports.add("tennis"); //index 1 sports.add("baseball"); //index 2 sports.add("golf"); //index 3 sports.add("volleyball"); //index 4 //Making ArrayList read only List<String> readOnlyList= Collections.unmodifiableList(sports); //Read operation, reading element with index 1 System.out.println(readOnlyList.get(1)); //Search operation, finding the index of "golf" element System.out.println(readOnlyList.indexOf("golf")); } }
Output:
tennis 3