In Java, how can you make an ArrayList read-only (so that no one can add elements, edit, or delete elements) after initialization?
Pass the collection object to its equivalent unmodifiable function of Collections class. The following code shows use of unmodifiableList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Temp {
public static void main(String[] args) {
List objList = new ArrayList();
objList.add(4);
objList.add(5);
objList.add(6);
objList.add(7);
objList = Collections.unmodifiableList(objList);
System.out.println("List contents " + objList);
try {
objList.add(9);
} catch(UnsupportedOperationException e) {
e.printStackTrace();
System.out.println("Exception occured");
}
System.out.println("List contents " + objList);
}
}
same way you can create other collections unmodifiable as well