java.util.Collections.unmodifiableCollection() Method

Advertisements


Description

The unmodifiableCollection() method is used to return an unmodifiable view of the specified collection.And an attempt to modify the collection will result in an UnsupportedOperationException.

Declaration

Following is the declaration for java.util.Collections.unmodifiableCollection() method.

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

Parameters

  • c--This is the collection for which an unmodifiable view is to be returned.

Return Value

  • The method call returns an unmodifiable view of the specified collection.

Exception

  • NA

Example

The following example shows the usage of java.util.Collections.unmodifiableCollection()

package com.tutorialspoint;

import java.util.*;

public class CollectionsDemo {
   public static void main(String[] args) {
      // create array list
      List<Character> list = new ArrayList<Character>();
      
      // populate the list
      list.add('X');
      list.add('Y');
      
      System.out.println("Initial list: "+ list);
      
      Collection<Character> immutablelist = Collections.unmodifiableCollection(list);
      
      // try to modify the list
      immutablelist.add('Z');      
   }
}

Let us compile and run the above program, this will produce the following result.

Initial list: [X, Y]
Exception in thread "main" java.lang.UnsupportedOperationException



Advertisements
Advertisements