make ArrayList Read only
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 ArrayList
into Collections.unmodifiableList()
. It returns an unmodifiable view of the specified list. Only use this returned List
, and never the original ArrayList
.
Pass the list object to Collections.unmodifiableList()
. See the example below.
import java.util.*;
public class CollDemo
{
public static void main(String[] argv) throws Exception
{
List stuff = Arrays.asList(new String[] { "a", "b" });
List list = new ArrayList(stuff);
list = Collections.unmodifiableList(list);
Set set = new HashSet(stuff);
set = Collections.unmodifiableSet(set);
Map map = new HashMap();
map = Collections.unmodifiableMap(map);
System.out.println("Collection is read-only now.");
}
}
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<Integer> objList = new ArrayList<Integer>();
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
Collections.unmodifiableMap(map)
Collections.unmodifiableSet(set)
Are you sure you want to use an ArrayList
in this case?
Maybe it would be better to first populate an ArrayList
with all of your information, and then convert the ArrayList
into a final array when the Java program initializes.