Java Utility Library

Java Collections - checkedCollection() Method



The java.util.Collections.checkedCollection() method returns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException.

Syntax

public static <E> Collection<E> checkedCollection(Collection<E> c,
                                                  Class<E> type)

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


Parameters

c Specify the collection for which a dynamically typesafe view is to be returned.
type Specify the type of element that c is permitted to hold.

Return Value

Returns a dynamically typesafe view of the specified collection.

Exception

NA.

Example:

In the example below, the java.util.Collections.checkedCollection() method returns a dynamically typesafe 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 a dynamically typesafe view
    //of the collection
    Collection NewList = Collections.checkedCollection(MyList, Integer.class);

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

The output of the above code will be:

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

❮ Java.util - Collections