104
Java Collections unmodifiableList() Method
The unmodifiableList() method of Java Collections class is used to get an unmodifiable view of the specified list. If any attempt occurs to modify the returned list whether direct or via its iterator, results in an UnsupportedOperationException.
Syntax
Following is the declaration of unmodifiableList() method:
Parameter
Parameter | Description | Required/Optional |
---|---|---|
list | It is the list for which an unmodifiable view is to be returned. | Required |
Returns
The unmodifiableList() method returns an unmodifiable view of the specified list.
Exceptions
NA
Example 1
Output:
Unmodifiable List: [Google, Mozila FireFox, Yahoo] Unmodifiable List after adding element to the list:[Google, Mozila FireFox, Yahoo, Safari]
Example 2
Output:
Unmodifiable List: [Google, Mozila FireFox, Yahoo] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056) at myPackage.UnmodifiableListExample2.main(UnmodifiableListExample2.java:9)
Example 3
Output:
Unmodifiable list: [10, 20, 30, 40] Unmodifiable list after adding (50): [10, 20, 30, 40, 50]
Next TopicJava Collections Class