group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
255 Members
Join this group to post and comment.
DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
05 Feb 2019

How to make collection read only in java?

Read only collection or unmodifiable collection is a collection which can not be modified once created. You will not be able to add an element or remove an element or edit an element once you make the collection read only. If you try to perform these operations on read only collection, you will get java.lang.UnsupportedOperationException. In this post, we will see how to make collection read only in java.

java.util.Collections class provides some unmodifiable wrapper methods to create read only collections in java. These methods take the Collection type as an argument and returns read only view of the specified collection. Any modification operations (like add, delete or edit an element) on the returned collection, direct or via its iterators, will result in UnsupportedOperationException. But, you can perform any modification operations on original collection and those modifications are reflected in the returned collection.

That means, what these unmodifiable wrapper methods do is, any query or read operations you perform on the returned collection, will actually read through the original collection and any modification operations you perform on the returned  collection, direct or via its iterators, will result in UnsupportedOperationException.