gpt4 book ai didi

java - 使用新比较器时 TreeMap putall 问题

转载 作者:搜寻专家 更新时间:2023-11-01 03:20:38 26 4
gpt4 key购买 nike

TreeMap<String, Integer> map1 = new TreeMap<String, Integer>();
map1.put("A", 1); map1.put("B", 2); map1.put("C", 3);
TreeMap<String, Integer> map2 = new TreeMap<>((str1, str2) -> map1.get(str1) - map1.get(str2) > 0 ? -1 : 1);
map2.putAll(map1);
Iterator<String> iterator = map2.keySet().iterator();
while(iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " " + map2.get(key) + " " + map1.get(key));
}

这个的输出是

C  null 3

B null 2

A null 1

请解释为什么我从 map2 获取空值,即使在执行 map2.putAll(map1)

之后也是如此

奇怪的是,当我遍历入口迭代器时给出了正确的输出

    Iterator<Entry<String, Integer>> entryIterator = map2.entrySet().iterator();
while(entryIterator.hasNext()) {
Entry<String, Integer> entry = entryIterator.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}

编辑正如回答的问题是比较器。它正在与

    TreeMap<String, Integer> map2 = new TreeMap<>((str1, str2) -> str1.equals(str2) ? 0 : map1.get(str1) - map1.get(str2) > 0 ? -1 : 1);

最佳答案

当映射值相等时,您错过了在比较器中返回零:

TreeMap<String, Integer> map2 = new TreeMap<>(
new Comparator<String>() {

@Override
public int compare(String str1, String str2) {
if(map1.get(str1).equals(map1.get(str2))) {
return 0;
}
return map1.get(str1) - map1.get(str2) > 0 ? -1 : 1;
}
});

来自 TreeMap 的文档:

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

关于java - 使用新比较器时 TreeMap putall 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470169/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com