1

This is my code

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

I get this exception:

SetTest$Node cannot be cast to java.lang.Comparable

You can see that the Node class already implants comparable, why the cast doesn't work as expected then?

Jack Thomson
  • 193
  • 8
  • 1
    [`Comparable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html) isn't the same as [`Comparator`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html). – Andy Turner Feb 22 '20 at 19:27

1 Answers1

1

Replace

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

with

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;
    }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110