Iterate Over Unmodifiable Collection in Java
The Collection is a framework that provides an architecture to store and manipulate the group of objects. In Java Collections, we perform operations like searching, sorting, Iterating over the given set of elements.
Modifiable: Modifiable means we can perform operations like adding, deleting, updating elements in collection data structures.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Example: Java List provides modification methods which include, add() method to add the elements in a list, replaceall() method to change the elements in a list.
Unmodifiable: Unmodifiable means we cannot perform adding, deleting, updating elements in collection data structures.
Example: We can initialize the modifiable class before any data structure so that we can prevent it from updating of any elements in the given data structure. We can create an unmodifiable view of a collection using Collections.unmodifiableCollection(collection)
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
Parameters: This method takes the collection as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified collection.
Element are added to the list: geeks for geeks welcome to geeks for geeks This is Unmodifiable Collection
welcome to geeks for geeks
Example 3: For UnsupportedOperationException
Initial list: [Geeks, for] Trying to modify the unmodifiableCollection Exception thrown : java.lang.UnsupportedOperationException