How to make ArrayList Read Only?

The read-only means unmodifiable view of Collection in which we can not perform any operation which will change the collection through add(), remove() or set() method. We can obtain read-only collection from the existing collection by calling Collections.unmodifiableCollection() method.

Output:

    Exception in thread "main"java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
at collectionInterview.list.UnmodifiableArrayList.main(UnmodifiableArrayList.java:20)

Here we have converted the existing list fruitList to unmodifiable List. If we alter the "unmodifiableList", it will cause UnsupportedOperationException. We can still change the list with fruitList reference. like calling:





Latest Courses