以下是我尝试过的内容。不确定这是否是findbugs给出错误的原因。
请参见下面的代码,其中包含
compareTo
方法的假设实现。
比较相同的对象会产生不同的输出结果。
public class Main
{
public static void main(String[] args)
{
Impl implAssignedToImpl = new Impl(1, 2, 3);
Impl otherImpl = new Impl(3, 2, 1);
System.out.println(implAssignedToImpl.compareTo(otherImpl));
AbstractBase implAssignedToAbstract = implAssignedToImpl;
System.out.println(implAssignedToAbstract.compareTo(otherImpl));
}
}
class AbstractBase implements Comparable<AbstractBase>
{
private int a;
private int b;
public AbstractBase(int a, int b)
{
super();
this.a = a;
this.b = b;
}
public int compareTo(AbstractBase other)
{
return (a + b) - (other.a + other.b);
}
}
class Impl extends AbstractBase
{
private int c;
public Impl(int a, int b, int c)
{
super(a, b);
this.c = c;
}
public int compareTo(Impl other)
{
return super.compareTo(other) + (c - other.c);
}
}
在我的假设的
compareTo
的基础上,以下似乎是一个不错的解决方案。您可以尝试有一个类似于
getSum
的方法,为对象实例赋值。
public class Main
{
public static void main(String[] args)
{
Impl implAssignedToImpl = new Impl(1, 2, 3);
Impl otherImpl = new Impl(3, 2, 1);
System.out.println(implAssignedToImpl.compareTo(otherImpl));
AbstractBase implAssignedToAbstract = implAssignedToImpl;
System.out.println(implAssignedToAbstract.compareTo(otherImpl));
}
}
class AbstractBase implements Comparable<AbstractBase>
{
private int a;
private int b;
public AbstractBase(int a, int b)
{
super();
this.a = a;
this.b = b;
}
public int compareTo(AbstractBase other)
{
return getSum() - other.getSum();
}
public int getSum()
{
return a + b;
}
}
class Impl extends AbstractBase
{
private int c;
public Impl(int a, int b, int c)
{
super(a, b);
this.c = c;
}
@Override
public int getSum()
{
return super.getSum() + c;
}
}
Impl
中,你正在重载(尝试在那里放置@Override
)。 - pingw33nImpl
里面使用的compareTo(Impl other)
,是一个常见错误,它不会像预期那样运行。它没有重写 Comparable 接口的方法。 - RadiodefAbstractBase
的子类A
和B
的实例a
和b
:即使它们来自不同的子类,你是否希望将a
和b
进行比较(即,你是否希望将AbstractBase
的任何实例与其他任何实例进行比较)?或者你想指定每个AbstractBase
的子类S
需要能够将其自己的实例相互比较,但不一定需要将其自己的实例与其他子类的实例进行比较? - DirkComparator<Impl>
,并在排序过程中使用它。 - Duncan Jones