[英]ClassCastException when inserting into a TreeSet
Having the following Java TreeSet 具有以下Java TreeSet
TreeSet<Widget> tabs = new TreeSet<Widget>();
When I do tabs.add(new Widget());
当我做tabs.add(new Widget());
in method a() it worked. 在方法a()中它起作用了。 When I do the same in method b() shortly after the first insert is performed I the a ClassCastException. 当我在第一次执行插入后不久在方法b()中执行相同的操作时,我发生了ClassCastException。
Change 更改
ArrayList<Widget> tabs = new ArrayList<Widget>();
It works fine in both methods a() and b() without any error. 它在方法a()和b()中都可以正常工作,没有任何错误。 I was wondering why there is a ClassCastException in the first example. 我想知道为什么第一个示例中存在ClassCastException。 There is no casting in place. 没有适当的转换。
Edit: Here are method a, b and the Widget class: 编辑:这是方法a,b和Widget类:
private void a() {
tabs.add(new Widget());
}
private void b() {
tabs.add(new Widget());
}
public class Widget() {}
How do I make the first example to work? 我如何使第一个示例起作用?
When you add to a TreeSet
, the object you pass must either implement Comparable
or you must specify a Comparator
at the time the TreeSet
is constructed. 当添加到TreeSet
,传递的对象必须实现Comparable
或者必须在构造TreeSet
时指定Comparator
。
The elements are ordered using their natural ordering, or by a
Comparator
provided at set creation time, depending on which constructor is used. 元素使用其自然顺序进行排序,或通过在设置创建时提供的Comparator
排序,具体取决于所使用的构造函数。
And the JavaDoc for TreeSet.add(E)
even tells you why this happens... 而且TreeSet.add(E)
的JavaDoc甚至告诉您为什么会发生这种情况...
ClassCastException - if the specified object cannot be compared with the elements currently in this set ClassCastException- 如果无法将指定对象与此集合中当前的元素进行比较
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.