Home » Java Collections unmodifiableCollection() Method with Examples

Java Collections unmodifiableCollection() Method with Examples

by Online Tutorials Library

Java Collections unmodifiableCollection() Method

The unmodifiableCollection() method of Java Collections class is used to get an unmodifiable view of the specified collection. If any attempt occurs to modify the returned collection whether direct or via its iterator, result in an UnsupportedOperationException.

Syntax

Following is the declaration of unmodifiableCollection() method:

Parameter

Parameter Description Required/Optional
c It is the collection for which an unmodifiable view is to be returned. Required

Returns

The unmodifiableCollection() method returns an unmodifiable view of the specified collection.

Exceptions

NA

Example 1

Test it Now

Output:

Unmodifiable Collection: [Google, Mozila FireFox, Yahoo]  Unmodifiable Collection after adding element to the original one:  [Google, Mozila FireFox, Yahoo, Safari]  

Example 2

Test it Now

Output:

Initial Collection: [Google, Mozila FireFox, Yahoo]  Exception in thread "main" java.lang.UnsupportedOperationException  at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1056)  at myPackage.UnmodifiableCollectionExample2.main(UnmodifiableCollectionExample2.java:9)   

Example 3

Test it Now

Output:

Unmodifiable collection: [10, 20, 30, 40]  Unmodifiable collection after adding (50): [10, 20, 30, 40, 50]  

You may also like