在Java 1.5和Java 1.7中覆盖“compare()”时,不返回0的缺点 [英] Drawbacks of not returning 0 when overriding 'compare()' in Java 1.5 and Java 1.7

查看:502
本文介绍了在Java 1.5和Java 1.7中覆盖“compare()”时,不返回0的缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我写的基于成本对节点排序的比较器。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆