Java Utility Library

Java Collections - unmodifiableCollection() Method



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

Syntax

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)

Here, T is the type of element in the collection.


Parameters

c Specify the collection for which an unmodifiable view is to be returned.

Return Value

Returns an unmodifiable view of the specified collection.

Exception

NA.

Example:

In the example below, the java.util.Collections.unmodifiableCollection() method returns an unmodifiable view of the given collection.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a collection list object
    Collection<Integer> MyList = new ArrayList<Integer>();

    //populating the list
    MyList.add(10);
    MyList.add(20);
    MyList.add(30);
    MyList.add(40);

    //printing the list
    System.out.println("MyList contains: " + MyList); 

    //creating an unmodifiable view of the collection
    Collection NewList = Collections.unmodifiableCollection(MyList);

    //printing the unmodifiable collection
    System.out.println("NewList contains: " + NewList); 

    //trying to modify the NewList
    NewList.add(50);     
  }
}

The output of the above code will be:

MyList contains: [10, 20, 30, 40]
NewList contains: [10, 20, 30, 40]

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
    at MyClass.main(MyClass.java:24)

❮ Java.util - Collections