在Java 1.5和Java 1.7中覆盖“compare()”时,不返回0的缺点 [英] 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;
}
}
我发现它的行为在我的机器上不同Java 1.7)和Uni的服务器(Java 1.5)。但是当我这样做:
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)
工作罚款在1.5,但另一方面在1.7。
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?
推荐答案
缺点是 TreeSet
, TreeMap
,基本上所有基于比较的数据结构都不会工作。甚至一点点。特别是 TreeSet.contains
将总是返回 false
和 TreeMap.get
将始终返回null。
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.
这篇关于在Java 1.5和Java 1.7中覆盖“compare()”时,不返回0的缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!