Why doesn't TreeSet.contains () work?

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 is it throwing ClassCastException?

+5
source share
4 answers

When creating an instance TreeSetwithout an explicit comparator, it expects the inserted elements to implement Comparablebut Classnot implement this interface.

To fix, create a comparator for Class:

Comparator<Class> classComp = new Comparator<Class>()
{
    @Override
    public int compare(Class o1, Class o2)
    {
        return o1.getName().compareTo(o2.getName());
    }
};
TreeSet<Class> classes = new TreeSet<Class>(classComp);
+8
source

TreeSet- an ordered set, so any element you add must implement Comparable(unless you specify a custom one Comparator). Classdoes not work.

, , HashSet. .

Javadoc ( ):

NavigableSet TreeMap. , , , .

(n) (, ).

, , ( , ) , Set. (. , ). , Set , TreeSet compareTo ( compare), , , , . ; Set.

: Comparator

+3

Blockquote ClassCastException?

This was caused by the implementation of TreeMap, on the basis of which TreeSet, which is a key set of TreeMap, is based.

java.lang.Class does not implement the java.lang.Comparable interface, so it throws a ClassCastException.

+1
source

Actual error java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.Comparable . Here it is - TreeSet imposes order on the elements. If you use a HashSet, everything is fine.

0
source

All Articles