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 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.");
}
}