Java TreeMap重复键 [英] Java TreeMap Duplicate Keys

查看:934
本文介绍了Java TreeMap重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可能在Java中发现了一个错误。

I think I may have found a bug in Java.

我有一个TreeMap,我在其中使用自定义比较器。但是,当我把(键,值)放在已经存在的键上时,它似乎不会覆盖键,从而创建重复的键。我想我已经验证了这一点,因为我尝试过:

I have a TreeMap in which I use a custom comparator. However, it seems when I put(key, value), on a key that already exists, it does not override the key, thus creating duplicate keys. I think I have verified this because I tried:

System.out.println(testMap.firstKey().equals(testMap.lastKey()));

这打印出来是真的。有人知道为什么会这样吗?

And this prints out true. Anyone know why this is happening?

这是比较器代码:

private class TestComp implements Comparator<String> {
    @Override
    public int compare(String s1, String s2){

        if (s1.equals(s2)) {
            return 0;
        }
        int temp = otherMap.get(s1).compareTo(otherMap.get(s2));
        if (temp > 0) {
            return 1;
        }
        return -1;

    }


推荐答案

比较器总是需要返回一致的结果,并且当在TreeMap中使用时,与equals一致。

A comparator always needs to return consistent results, and when used in a TreeMap, be consistent with equals.

在这种情况下,你的比较器违反了第一个约束,因为它不一定给出一致性结果。

In this case your comparator violates the first constraint since it does not necessarily give consistent results.

示例:如果例如 otherMap maps

Example: If for instance otherMap maps

"a" -> "someString"
"b" -> "someString"

然后两个比较(a,b) 比较(b,a)将返回 -1

请注意,如果将实施更改为

Note that if you change the implementation to

if (s1.equals(s2)) {
    return 0;
}
return otherMap.get(s1).compareTo(otherMap.get(s2));

你打破了与equals一致的其他标准,因为 otherMap.get (s1).compareTo(otherMap.get(s2))可能会返回 0 ,即使 s1 不等于 s2

you break the other criteria of being consistent with equals, since otherMap.get(s1).compareTo(otherMap.get(s2)) might return 0 even though s1 does not equal s2.

我已经详细说明了在一个自我回答的后续问题中这里

I've elaborated on this in a self-answered follow up question here.

来自评论:


即使比较器给出不一致的结果,Java语言是否仍然不允许重复键?

Even if a comparator gives inconsistent results, shouldn't the Java language still not allow duplicate keys?

不,当您插入一个键时,TreeMap将使用比较器搜索数据结构以查看该键是否已存在。如果比较器给出不一致的结果,TreeMap可能查看错误的地方并断定该键不存在,从而导致未定义的行为。

No, when you insert a key, the TreeMap will use the comparator to search the data structure to see if the key already exists. If the comparator gives inconsistent results, the TreeMap might look in the wrong place and conclude that the key does not exist, leading to undefined behavior.

这篇关于Java TreeMap重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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