Why does TreeSet throw a ClassCastException?

大憨熊 提交于 2019-11-27 01:44:54

Either Employee has to implement Comparable, or you need to provide a comparator when creating the TreeSet.

This is spelled out in the documentation for SortedSet:

All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.

If you don't fulfil these requirements, the sorted set won't know how to compare its elements and won't be able to function.

denis.solonenko

TreeSet requires elements to implement the Comparable interface if a custom Comparator is not set. HashSet uses the equals/hashCode contract instead.

You can add only one element into TreeSet which does not implement Comparable because it does not need to be compared with other elements.

Take a look at the TreeMap.put(K key, V value) source code and you'll clearly see the reasons behind all your questions (TreeSet is based on TreeMap, hence the source reference).

From TreeSet#add(E) JavaDoc:

Throws: ClassCastException - if the specified object cannot be compared with the elements currently in this set

Basically what you need is to let Employee implement Comparable or provide a Comparator to the TreeSet object.

If you check TreeMap code you will see that if the comparator wasn't found within the Map object, it will try to cast the key (your Employee object) directly to Comparator:

...
Comparable<? super K> k = (Comparable<? super K>) key;
...

So implement Comparable interface to Employee object as it`s needed when you are using TreeSet, because TreeSet wants to keep elements sorted.

Marco Forberg

TreeSet is an implementation of SortedSet. You can either let Employee implement the Comparable interface or provide an appropriate Comparator for your TreeSet:

Set<Employee> s = new TreeSet<Employee>(new EmployeeComparator());
//class Employee
    public class Employee implements Comparable<Employee>{
    int id;

    Employee(int id){
    this.id=id;
    }

    public int compareTo(Employee e){ //implementing abstract method.
    if(id>e.id){
    return 1;
    }
    return 0;
    }


//class TreeSet

    Set<Employee> emp =new TreeSet<Employee>();

    Employee eobj1 = new Employee(2);
    Employee eobj2 = new Employee(3);
    emp.add(eobj1);
    emp.add(eobj2);

    for (Student ss:emp) {
    System.out.println(ss.rollno);
    }
}
//output: 2
//        3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!