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

标签 java

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/

相关文章:

java - 这是什么() ?它可以有多个参数吗?

java - 帕斯卡三角形 Java

java - Java 不一致状态比较

java - 从(子)目录中的文件读取文本

java - Android 中 Locale.getAvailableLocale 和 assetManager.getLocale 之间的区别?

java - 算法复杂度分析混淆

java - 如何按前缀整数值对 ArrayList<String> 进行排序

java - Play Framework : No @javax. persistence.Id 字段在类中找到

java - 访问内部类方法会导致 nullpointerException

java - 在 netbeans 中的尖括号之间拆分传入数据