- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
对于代码:
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
。
最佳答案
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/
如何判断两个TreeSet对象是否相等?我使用open-jdk-10。 ModifiebleObject class ModifiebleObject implements Comparable{
我正在使用 TreeSet 并在调用 TreeSet#add() 方法时发现了 ClassCastException。 代码: public class Testing { public st
假设我有一个自然排序的 TreeSet。我可以使用什么接口(interface)和方法来使新的 TreeSet 保持与第一个列表相同的顺序。 最佳答案 使用相同的Comparator(如果您的元素实现
是否有与 java.util.TreeSet 等效的 VB.NET? 最佳答案 您会发现最接近的是 SortedSet(T) class . 关于treeset - VB.NET 相当于 java.u
我有一个 TreeMap,其中的值是 TreeSet。现在我需要遍历键,对于 TreeSet 的每个元素,我必须删除该元素(然后继续做某事),然后删除该 TreeSet 的第二个元素等。 我试过: f
我今天接受了采访,接受我采访的人对他的陈述感到困惑,询问是否有可能 TreeSet等于 HashSet但不是 HashSet等于 TreeSet .我说“不”,但据他说,答案是"is"。 怎么可能?
这对我来说是一个很深的谜。 看看这个: TreeSet s = new TreeSet(); s.add(Long.valueOf(1)); s.add(Long.valueOf(4)); s.add
如果我想在 Java 的 TreeSet 中删除 log(n) 时间内的最高条目,我使用 treeSet.pollFirst() - Scala 的 mutable.TreeSet 类的等价物是什么?
例如,有一个二叉搜索树,其中包含一系列值。在添加新值之前,我需要检查它是否已经包含它“几乎重复”。我有 Java 解决方案,它只是执行地板和天花板以及完成这项工作的进一步条件。 JAVA : 给定一个
作为最佳实践, float 的集合类型实例不应超过一个。例如,Nil 是 scala 库中的一个 case 对象。 但是, TreeMap 和 TreeSet 在每次 empty() 调用时都会创建一
1、TreeSet 概述 1、TreeSet是 SortedSet 接口的实现类, TreeSet 可以确保集合元素处于排序状态。 2、TreeSet顾名思义他内部维护的是一个TreeMap,
我正在尝试创建一个 TreeSet 来对插入的字符串进行升序排序。我正在使用以下代码在 TreeSet 中输入值。 TreeSet ts = new TreeSet(); ts.add("@Test0
对于此作业,我需要将每个包含 2 个字符串的自定义数据类(称为 User)的实例保存到 TreeSet 中。然后,我必须在我创建的 TreeSet 中搜索从另一个文件的每一行中提取的字符串。第一个文件
好的,我有这个问题要解决: 创建一个名为 VirtualLibrary 的泛型类具有单个属性 totalNumberOfEntries , 以及使用户能够设置和返回条目的方法。条目类型为 Book ,
我不知道如何解释/理解以下有关 TreeSet 和 map 函数的行为。 我想我遗漏了一 block 拼图。任何有关此事的线索都将受到欢迎。 scala> class Person(val name:
我有一个间隔的TreeSet(带有开始和结束的案例类)。如果对此树集进行过滤,例如 treeSet.filter(x => input = x.start) 这预计会在 logN 时间内运行吗? 最佳
我需要一种方法来非常快速地计算整数 TreeSet 中小于 X 的元素数量。 我可以使用 子集() headSet() tailSet() 方法,但它们真的很慢(我只需要计数,而不是数字本身)。有办法
我是java新手,我正在尝试访问与其他类不同的类中的ArrayList和TreeSet。我知道这种从一个类访问它的方式。 这是我拥有 TreeSet 的类(class): public class
这个问题已经有答案了: Java : Comparable vs Comparator [duplicate] (2 个回答) 已关闭 3 年前。 这是我的代码 public class SetTes
我需要保留一个排序的节点列表,从第一个开始,然后获取所有相邻节点。第一个节点和所有其他节点都带有一个种子值,用于根据最低种子值确定接下来将使用哪个节点,一旦一个节点被用于获取相邻节点,它就会被标记为已
我是一名优秀的程序员,十分优秀!