有人可以用简单的语言解释我,为什么这个代码会抛出异常,"比较方法违反了它的一般合同!",我该如何修复它?
private int compareParents(Foo s1, Foo s2) {
if (s1.getParent() == s2) return -1;
if (s2.getParent() == s1) return 1;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我写了以下代码:
public class NewClass2 implements Comparator<Point>
{
public int compare(Point p1, Point p2)
{
return (int)(p1.getY() - p2.getY());
}
}
Run Code Online (Sandbox Code Playgroud)
如果我说有两个双号,3.2 - 3.1差异应该是0.1.然而,当我将数字转换为int时,差异最终为0,这是不正确的.
因此我需要compare()返回一个double,而不是int.问题是,我的getX领域是双重的.我怎么解决这个问题?