【问题标题】:Java TreeSet doesn't accept a customer object that already implements comparable [duplicate]Java TreeSet 不接受已经实现可比较的客户对象 [重复]
【发布时间】: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 类已经植入了可比性,为什么演员表没有按预期工作?

【问题讨论】:

标签: java collections


【解决方案1】:

替换

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;
    }
}

与

static class Node implements Comparable<Node> {
    int id;

    public Node(int id) {
        this.id = id;

    }
    @Override
    public int compareTo(Node o) {
        // Or, easier: return Integer.compare(this.id, o.id);
        if (this.id < o.id)
            return -1;
        if (this.id > o.id)
            return 1;
        return 0;
    }
}

【讨论】:

  • (并将compare(Node, Node) 替换为compareTo(Node) 的适当实现)
  • 谢谢,@AndyTurner。我刚刚更新了答案以完成缺失的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多