Search code examples
comparejavacomparatorcomparable

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


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?


Solution

  • 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.