How to check If the Specified Set is a Dynamically Typesafe View in Java


In this example, let’s see how to check if the specified set is a dynamically typesafe view with Collections.checkedSet().

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
 
public class CheckedSetExample {
 
    public static void main(String a[]){
         
        Set set = new HashSet();
        set.add("java");
        Set checkedSet = Collections.checkedSet(set, String.class);
        //You can add any type into set.
        set.add("example");
        System.out.println("Checked set: " + checkedSet);
        //You cannot add the wrong type into checkedSet.
        checkedSet.add(1);
    }
}

Output:

Checked set: [java, example]
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.CheckedSetExample.main(CheckedSetExample.java:18)

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments