Why does TreeSet throw a ClassCastException?

前端 未结 6 824
遥遥无期
遥遥无期 2020-11-29 06:30

I am trying to add two \'Employee\' objects to a TreeSet:

Set s = new TreeSet();
s.add(new Employee(1001));
s.add(new Employe         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 07:25

    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 k = (Comparable) key;
    ...
    

提交回复
热议问题