Why does TreeSet throw a ClassCastException?

前端 未结 6 815
遥遥无期
遥遥无期 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:09

    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.

提交回复
热议问题