2

编译器说“找不到符号:方法 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;
    }
}
4

3 回答 3

4

您也需要范围ObjectTypeComparable因为委派给:OBTComparable compareTo()ObjectType

如果更改<ObjectType><ObjectType extends Comparable<ObjectType>>,它将编译:

public class OBTComparable<ObjectType extends Comparable<ObjectType>> implements Comparable<OBTComparable>
于 2012-03-30T23:32:59.523 回答
3

我认为这是您正在寻找的正确代码(为了清楚起见,我替换ObjectTypeT):

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

我在这里改变了什么:

  1. OBTComparable 使用类型参数,因此您应该在实现时显示它Comparable。因此,您拥有implements Comparable<OBTComparable<T>>而不是简单地implements Comparable<OBTComparable>.
  2. 您在方法中比较了两个对象compareTo,但它们是否具有可比性?为确保满足此要求,您应该编写OBTComparable<T extends Comparable<T>>而不是仅OBTComparable<T>. 然后你会知道你可以打电话compareTo
于 2012-03-30T23:34:15.437 回答
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);
}
于 2012-03-30T23:31:48.823 回答