为什么 TreeSet 会抛出 ClassCastException? [英] Why does TreeSet throw a ClassCastException?

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

问题描述

我正在尝试向 TreeSet 添加两个员工"对象:

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

Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));

但它抛出一个 ClassCastException:

But it throws a 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)

但是如果我只向 TreeSet 添加一个对象:

But if I add only one object to the TreeSet:

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

或者如果我使用 HashSet 代替:

Or if I use a HashSet instead:

Set<Employee> s = new HashSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));

那么就成功了.为什么会发生异常,我该如何解决?

Then it is successful. Why does the exception happen and how do I fix it?

推荐答案

Employee 必须实现 Comparable,或者你需要在创建 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))不得抛出 ClassCastException 用于排序集中的任何元素 e1e2.试图违反此限制将导致违规方法或构造函数调用抛出 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天全站免登陆