编译器说“找不到符号:方法compareTo(java.lang.Object)”。你能告诉我这里的错误在哪里吗?
以下是代码的一部分:
public class OBTComparable<ObjectType> implements Comparable<OBTComparable>
{
public OTBComparable leftNode = null;
public OBTComparable mainNode = null;
public OBTComparable rightNode = null;
public ObjectType object = null;
public OBTComparable(ObjectType requiredObject)
{
object = requiredObject;
}
@Override
public int compareTo(OBTComparable other)
{
if(object.compareTo(other.object) == 0)
return 0;
else
if (object.compareTo(other.object) > 0)
return 1;
else return -1;
}
}
答案 0 :(得分:4)
您需要将ObjectType
范围限定为Comparable
,因为OBTComparable
为delegating compareTo()
至ObjectType
:
如果您将<ObjectType>
更改为<ObjectType extends Comparable<ObjectType>>
,则会编译:
public class OBTComparable<ObjectType extends Comparable<ObjectType>> implements Comparable<OBTComparable>
答案 1 :(得分:3)
我认为这是您正在寻找的正确代码(为了清晰起见,我将ObjectType
替换为T
):
class OBTComparable<T extends Comparable<? super T>> implements Comparable<OBTComparable<T>> {
public OBTComparable<T> leftNode = null;
public OBTComparable<T> mainNode = null;
public OBTComparable<T> rightNode = null;
public T object = null;
public OBTComparable(T requiredObject) {
object = requiredObject;
}
@Override
public int compareTo(OBTComparable<T> other) {
if (object.compareTo(other.object) == 0) {
return 0;
} else if (object.compareTo(other.object) > 0) {
return 1;
} else return -1;
}
}
我在这里做了什么改变:
Comparable
时显示它。因此,您只需implements Comparable<OBTComparable<T>>
而非implements Comparable<OBTComparable>
。compareTo
方法中比较了两个对象,但它们是否具有可比性?为确保满足此要求,您应该编写OBTComparable<T extends Comparable<T>>
而不是OBTComparable<T>
。然后您就会知道可以致电compareTo
。答案 2 :(得分:2)
ObjectType还必须实现Comparable<ObjectType>
。
如果你这样做,我相信这一点:
public int compareTo(OBTComparable other)
{
if(object.compareTo(other.object) == 0)
return 0;
else
if (object.compareTo(other.object) > 0)
return 1;
else return -1;
}
可以简化为:
public int compareTo(OBTComparable other)
{
return object.compareTo(other.object);
}