Using checkedSet:
package com.logicbig.example.collections;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class CheckedSetExample2 {
public static void main(String... args) {
Set<Integer> set = new HashSet<>();
set = Collections.checkedSet(set, Integer.class);
set.add(1);
System.out.println(set);
Set set2 = set;
set2.add("two");
System.out.println(set2);
}
}
Output
Caused by: java.lang.ClassCastException: Attempt to insert class java.lang.String element into collection with element type class java.lang.Integer
at java.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
at java.util.Collections$CheckedCollection.add(Collections.java:3080)
at com.logicbig.example.collections.CheckedSetExample2.main(CheckedSetExample2.java:22)
... 6 more