gpt4 book ai didi

java - Set 引用变量中的 TreeSet 实例

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:45 25 4
gpt4 key购买 nike

对于代码:

Set<Phone> set = new TreeSet<>();
set.add(new Phone("Harry"));

我得到错误:

Phone cannot be cast to java.base/java.lang.Comparable

如果引用变量是 Set 类型,为什么 Phone 必须实现 Comparable?

如果引用变量是TreeSet,那么Phone类当然必须实现Comparable

最佳答案

查看Javadoc for TreeSet() :

Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface.

元素必须具有某种可比性,因为 TreeSet 是一个 SortedSet。请注意,Set 不一定是无序的,只是 Set 接口(interface)未指定顺序。允许实现类定义元素的顺序。

如果要将非 Comparable 实例插入比较器(或使用非自然顺序),则必须使用显式比较器调用构造函数。

Set <Phone> set = new TreeSet<>(someComparator);

关于java - Set 引用变量中的 TreeSet 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55020815/

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