gpt4 book ai didi

java - 为什么 TreeSet 声明为 TreeSet 而不是 TreeSet>

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:41 26 4
gpt4 key购买 nike

我正在使用 TreeSet 并在调用 TreeSet#add() 方法时发现了 ClassCastException

代码:

public class Testing {
public static void main(String[] args) {
TreeSet<Testing> ts = new TreeSet<>();
ts.add(new Testing());
}
}

输出:

Exception in thread "main" java.lang.ClassCastException: Testing cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1290)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at Testing.main(Testing.java:13)

很明显,因为 TreeSet 是一个有序集合,它需要 Comparable 对象来对它们进行排序,所以为什么不将其类型声明为 p>

public class TreeSet<E extends Comparable<E>>

并在编译时进行检查而不是在运行时抛出异常?

最佳答案

TreeSet 的元素不必实现 Comparable,因为您可以将 Comparator 传递给 TreeSet 之一 的构造函数,以便为未实现 Comparable 的元素(或当您想要使用排序时实现 Comparable 的元素强加顺序) Comparable 定义的自然顺序除外)。

关于java - 为什么 TreeSet 声明为 TreeSet<E> 而不是 TreeSet<E extends Comparable<E>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com