Drawbacks of not returning 0 when overriding '

2019-09-18 22:17发布

问题:

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.