【发布时间】:2020-06-06 21:42:28
【问题描述】:
这是我的代码
public class SetTest {
public static void main(String[] args) {
SortedSet<Node> sortedSet = new TreeSet<>();
PriorityQueue<Node> priorityQueue = new PriorityQueue<>();
for (int i = 0; i < 100; i++) {
Node node = new Node(i);
sortedSet.add(node);
priorityQueue.add(node);
}
sortedSet.iterator().forEachRemaining(s -> {
System.out.println(s.id);
});
}
static class Node implements Comparator<Node> {
int id;
public Node(int id) {
this.id = id;
}
@Override
public int compare(Node o1, Node o2) {
if (o1.id < o2.id)
return -1;
if (o1.id > o2.id)
return 1;
return 0;
}
}
}
我得到了这个例外:
SetTest$Node cannot be cast to java.lang.Comparable
您可以看到 Node 类已经植入了可比性,为什么演员表没有按预期工作?
【问题讨论】:
-
Comparable与Comparator不同。
标签: java collections