devxlogo

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.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

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.