Drawbacks of not returning 0 when overriding 'compare()' in Java 1.5 and Java 1.7

六眼飞鱼酱① 提交于 2019-12-11 18:28:13

问题


This is the comparator I wrote to to sort Nodes based on cost.

public class MyCostComparator implements Comparator<Node>{
    public int compare(Node a, Node b){
        if(a.pathCost > b.pathCost)
            return 1;
        else
            return -1;
    }
}

I find that it's behaviour is different on my machine (Java 1.7) and on the Uni's server (Java 1.5). However when I make it:

if(a.pathCost >= b.pathCost) , it seems to work fine on 1.5, but the other way on 1.7.

Also, what's the drawback of NOT returning zero when the values are equal?


回答1:


The "drawback" is that TreeSet, TreeMap, and basically all comparison-based data structures won't work at all. Not even a little bit. In particular, TreeSet.contains will always return false, and TreeMap.get will always return null.




回答2:


If you never return zero, then an object will appear not equal to itself. This violates the contract of Comparable and prevents any collection that relies on it from working properly (or at all).

Java 7 has also introduced a new kind of sorting algorithm for Collections.sort and will throw an IllegalArgumentException if it detects that the Comparable contract is violated. This is a change to earlier versions, which silently ignored the fact.



来源:https://stackoverflow.com/questions/14903104/drawbacks-of-not-returning-0-when-overriding-compare-in-java-1-5-and-java-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!