为什么TreeSet抛出ClassCastException [英] Why does TreeSet throws ClassCastException

查看:254
本文介绍了为什么TreeSet抛出ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我试图添加两个员工对象

In below code I am trying to add two employee object

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));

然后结果是成功没有异常。我没有在上面的代码中做任何类转换活动。请帮助我找出原因并建议我的解决方案。

Then result is success there is no exception. I am not doing any class casting activity in above code. Please help me to find out the cause and suggest me the solution.

推荐答案

员工必须实施 可比较的 ,否则您需要在创建 <$ c $时提供比较器 c> TreeSet 。

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

这在 SortedSet


插入到排序集合中的所有元素必须实现 Comparable 接口(或被指定的比较器接受)。此外,所有这些元素必须相互比较: e1.compareTo(e2)(或 comparator.compare(e1,e2))不得为任何元素 e1 e2 ClassCastException $ c>在排序集合。尝试违反此限制将导致冒犯方法或构造函数调用抛出 ClassCastException

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.

这篇关于为什么TreeSet抛出ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆