We can create Read only Collections by using
Collections.unmodifiableCollection() utility method. It returns unmodifiable or read only view of Collection in which you can not perform any operation that will change the collection like add , remove and set either directly or while iterating over iterator. It raises UnsupportedOperationException whenever you try to modify the List . If the list is read-only then you can not add or change any element of the list. We usually use this when we want to pass the collection, but does not want to the user to accidentally modify it.
Read only collection can also be called as unmodifiable or Immutable collection in Java.
The following methods make a Collection read only.
ReadOnlyCollectionsDemo CODE import java.util.ArrayList; OUTPUT We cannot modify a read only collection. DESCRIPTION At LINE A we created a list.At LINE B, LINE C we make a list as read only. At LINE D we created a hash map, make it as read only and modified. At LINE E, we are modifying the hash map and we are checking that it throws an THINGS TO TRY
ArrayList by using Arrays.asList(String[]{}) .
|