Stack Overflow Asked by ChalupaBatmac on December 5, 2021
I have the following class signatures:
public class SkipListSet<T extends Comparable<T>> implements SortedSet<T>
and another class outside of SkipListSet class:
class Node<T extends Comparable<T>>
The second one acts as a wrapper class that contains the following:
T data;
List<Node<T>> tower;
Node<T> nextNode = null;
Node<T> prevNode = null;
When I try implementing compareTo() method in my Node class:
public int compareTo(T somePayLoad) {
if (this.data < somePayLoad)
return -1;
else if (this.data > somePayLoad)
return 1;
else
return 0;
}
I get the following error:
SkipListSet.java:171: error: bad operand types for binary operator '<'
if (this.data < somePayLoad)
^
first type: T
second type: T
where T is a type-variable:
T extends Comparable<T> declared in class SkipListSet.Node
Why is it that I can’t compare two types of T data in my compareTo method?
You don't need to write the compareTo method. T class should implement Comparable inteface.
TestSkipListSet<NodeData> list = new TestSkipListSet<NodeData>();
TestSkipListSet<NodeData2> list2 = new TestSkipListSet<NodeData2>();
class NodeData implements Comparable<NodeData> {
int value;
@Override
public int compareTo(@NonNull NodeData o) {
return this.value - o.value;
}
}
class NodeData2 implements Comparable<NodeData2> {
TestUser value;
@Override
public int compareTo(@NonNull NodeData2 o) {
return this.value.age-o.value.age;
}
}
class TestUser{
int age;
}
public class TestSkipListSet<T extends Comparable<T>> implements SortedSet<T>{
...
}
Answered by simon5678 on December 5, 2021
You can't use '<' or '>' on objects. I think what you need is:
public int compareTo(T somePayLoad) {
return this.data.compareTo(somePayLoad.data);
}
(Add null checks).
Answered by FreeBird on December 5, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP