How can I compare two ListNode values to return 1 if ListNode o1.value > ListNode o2.value, return 0 if equal, and return -1 if less than.
I have this comparator right now but there is an error saying that abstract methods are not implemented. Also, I’m unsure if they will compare correctly for values such as the example below.
Add ‘d’. add ‘b’. add ‘e’
b->d->e
private Comparator<? super E> priorityComparator = new Comparator<E>(){
public int compare(ListNode<E> o1, ListNode<E> o2) {
String i1 = o1.value.toString();
String i2 = o2.value.toString();
return i1.compareTo(i2);
}};
How can I implement this comparator correctly so that it takes two ListNode objects and returns the int value comparison between them?
You’ve currently not implemented
Comparator<E>.compare– you’ve implementedComparator<ListNode<E>>.compare. You either need to change the type of your variable, or you need to change the parameters to the method. If you really want to make something which compares nodes, then you wantComparator<ListNode<E>>.Also note that your comparison only really works for types where
toString()is overridden in a manner which is compatible with its natural ordering. For example, it wouldn’t work well withListNode<Integer>, as it would claim that a value of 10 was less than a value of 2…