Collections checkedList() method in Java with Examples
Last Updated :
16 Jun, 2022
The checkedList() method of Collections class is present inside java.util package is used to return a dynamically typesafe view of the specified list. The key thing to note here is that the returned list will be serializable if the specified list is serializable. Since null is considered to be a value of any reference type, the returned list permits the insertion of null elements whenever the backing list does.
Tip: This method is compatible with java version 1.5 and onwards.
Syntax:
public static List
checkedList(List list, Class type)
Parameters: This method takes the following arguments as parameters:
- The list for which a dynamically typesafe view is to be returned
- The type of element that list is permitted to hold
Return Type: A dynamically typesafe view of the specified list.
Exceptions: This method throws ClassCastException
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( "A" );
arlst.add( "B" );
arlst.add( "C" );
arlst.add( "TajMahal" );
System.out.println( "List: " + arlst);
List<String> tslst = Collections.checkedList(
arlst, String. class );
System.out.println( "Typesafe view of List: "
+ tslst);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
List: [A, B, C, TajMahal]
Typesafe view of List: [A, B, C, 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);
List<Integer> tslst = Collections.checkedList(
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]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...