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?