Making a Read-only Collection

Making a Read-only Collection

The Collections class provides static APIs to generate read-only orunmodifiable collections, lists, sets, or maps from specified entities. For instance, if you are sure that the ArrayList you’ve made should not be modified, you can generate a read-only list from it using the following:

   ArrayList list = new ArrayList();  list.add("first");  ...  List readOnlyList = Collections.unmodifiableList(list);

It’s important to discard the previous reference to the modifiable object. In the above example, we can still alter the list using the “list” variable. Since this defies the purpose of generating an unmodifiable list, and one should not do this. Any attempt to modify such a read-only object would result in an UnsupportedOperationException.


Share the Post: