Home » Java Collections checkedList() Method with Examples

Java Collections checkedList() Method with Examples

by Online Tutorials Library

Java Collections checkedList() Method

The checkedList() is a method of Java Collections class which returns a dynamically typesafe view of the specified list. If an element inserted of the wrong type, it will result in an immediate ClassCastException.

Syntax

Following is the declaration of checkedList() method:

Parameter

Parameter Description Required/Optional
list It is the list for which a dynamically typesafe view is to be returned. Required
type It is the type of element that list is permitted to hold. Required

Returns

The checkedList() method returns a dynamically typesafe view of the specified List.

Exceptions

ClassCastException

Compatibility Version

Java 1.5 and above

Example 1

Test it Now

Output:

Type safe view of the List is: [A, B, C, D]  

Example 2

Test it Now

Output:

Checked list content: [one, two, three, four]  Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String  at java.base/java.util.Collections$CheckedCollection.typeCheck(Collections.java:3038)  at java.base/java.util.Collections$CheckedCollection.add(Collections.java:3081)  at myPackage.CollectionCheckedListExample2.main(CollectionCheckedListExample2.java:15)  

Example 3

Test it Now

Output:

Type safe view of the List is: [10, 20, 30, 40]  

Example 4

Test it Now

Output:

[RAJ]  [RAJ, 2]  

You may also like