devxlogo

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.

See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist