The checkedCollection() method of java.util.Collections class is used to return a dynamically typesafe view of the specified collection. The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object’s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list. The returned collection will be serializable if the specified collection is serializable.
Since null is considered to be a value of any reference type, the returned collection permits insertion of null elements whenever the backing collection does.
Syntax:
public static Collection
checkedCollection(Collection c, Class type)
Parameters: This method takes two parameters
- The collection for which a dynamically typesafe view is to be returned
- The type of element that c is permitted to hold
Return Type: This method returns a dynamically typesafe view of the specified collection
Example 1:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
try {
List<String> arlst = new ArrayList<String>();
arlst.add( "CSS" );
arlst.add( "PHP" );
arlst.add( "HTML" );
arlst.add( "TajMahal" );
System.out.println( "List: " + arlst);
Collection<String> tslst
= Collections.checkedCollection(
arlst, String. class );
System.out.println( "Typesafe view of List: "
+ tslst);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output: List: [CSS, PHP, HTML, TajMahal]
Typesafe view of List: [CSS, PHP, HTML, TajMahal]
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] argv) throws Exception
{
try {
List<Integer> arlst = new ArrayList<Integer>();
arlst.add( 20 );
arlst.add( 30 );
arlst.add( 40 );
arlst.add( 50 );
System.out.println( "List: " + arlst);
Collection<Integer> tslst
= Collections.checkedCollection(
arlst, Integer. class );
System.out.println( "Typesafe view of List: "
+ tslst);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output: List: [20, 30, 40, 50]
Typesafe view of List: [20, 30, 40, 50]