在下面的代码中,我试图添加两个员工对象
Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001)); s.add(new Employee(1002));
但结果是java.lang.classCastException:
Exception in thread "main" java.lang.classCastException: Employee cannot be cast to java.lang.Comparable at java.util.TreeMap.put(TreeMap.java:542) at java.util.TreeSet.add(TreeSet.java:238) at MyClient.main(MyClient.java:9)
但是如果我改变了
Set<Employee> s = new TreeSet<Employee>(); s.add(new Employee(1001));
要么
Set<Employee> s = new HashSet<Employee>(); s.add(new Employee(1001)); s.add(new Employee(1002));
解决方法
员工必须实施
Comparable
,或者在创建
TreeSet
时需要
provide a comparator.
在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)
(orcomparator.compare(e1,e2)
) must not throw aClassCastException
for any elementse1
ande2
in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw aClassCastException
.
如果您不符合这些要求,排序集将不知道如何比较其元素,并且无法正常工作.
原文地址:https://www.jb51.cc/java/123339.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。