public class Empty {
public static void main( String[] args ) {
TreeSet<Class> classes = new TreeSet<Class>();
classes.add( String.class );
String test = new String();
try{
if( classes.contains(test.getClass()) ){
System.out.println( "contains" );
}
}catch(ClassCastException cce){
System.out.println( "Expected: " + classes );
System.out.println( "But it was: " + test.getClass() );
}
}
}
Why does this throw a ClassCastException?
When instantiating
TreeSetwithout an explicit comparator, it expects inserted elements to implementComparable, butClassdoes not implement this interface.To fix, create a comparator for
Class: