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


In this example we will show how to check if the specified list is a dynamically typesafe view with Collections.checkedList().

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
 
public class CheckedListExample {
 
    public static void main(String a[]){
         
        List list = new ArrayList();
        list.add("java");
        List checkedList = Collections.checkedList(list, String.class);
        //You can add any type into List.
        list.add("example");
        System.out.println("Checked List: " + checkedList);
        //You cannot add the wrong type into 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.CheckedListExample.main(CheckedListExample.java:18)

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments