How to Check If the Specified Collection is a Dynamically Typesafe View in Java


Here let’s see how to check if the specified collection is a dynamically typesafe view using Collections.checkedCollection().

Source Code

package com.beginner.examples;

import java.util.Collection;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
 
public class CheckedCollectionExample {
 
    public static void main(String a[]){
         
        List list = new ArrayList();
        list.add("java");
        Collection checkedList = Collections.checkedCollection(list, String.class);
        //You can add any type into List.
        list.add("example");specified C
        System.out.println("Checked List: " + checkedList);
        //You cannot add the wrong type checkedList.
        checkedList.add(1);
    }
}

Output:

Checked List: [java, example]
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.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
	at java.util.Collections$CheckedCollection.add(Collections.java:3080)
	at com.beginner.examples.CheckedCollectionExample.main(CheckedCollectionExample.java:19)

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments