【问题标题】:Java TreeMap put vs HashMap put, custom Object as keyJava TreeMap put vs HashMap put,自定义对象作为键
【发布时间】:2020-09-23 02:57:34
【问题描述】:

我的目标是使用 TreeMap 来制作按 Box.volume 属性排序的 Box 键对象,同时能够通过 Box.code 放置不同的键。在 TreeMap 中是不可能的吗?

根据下面的测试 1,HashMap put 按预期工作,HashMap 保留 A、B 键对象,但在测试 2 中,TreeMap put 不将 D 视为不同的键,它替换C 的值,请注意我使用 TreeMap 比较器作为 Box.volume,因为 我希望在 TreeMap 中按音量对键进行排序

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        //test 1
        Box b1 = new Box("A");
        Box b2 = new Box("B");
        Map<Box, String> hashMap = new HashMap<>();
        hashMap.put(b1, "test1");
        hashMap.put(b2, "test2");
        hashMap.entrySet().stream().forEach(o-> System.out.println(o.getKey().code+":"+o.getValue()));
        //output
        A:test1
        B:test2

        //test 2
        Box b3 = new Box("C");
        Box b4 = new Box("D");
        Map<Box, String> treeMap = new TreeMap<>((a,b)-> Integer.compare(a.volume, b.volume));
        treeMap.put(b3, "test3");
        treeMap.put(b4, "test4");
        treeMap.entrySet().stream().forEach(o-> System.out.println(o.getKey().code+":"+o.getValue()));
        //output
        C:test4
    }
}

class Box {
    String code;
    int volume;

    public Box(String code) {
        this.code = code;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Box box = (Box) o;
        return code.equals(box.code);
    }

    @Override
    public int hashCode() {
        return Objects.hash(code);
    }
}

谢谢

【问题讨论】:

    标签: java hashmap treemap


    【解决方案1】:

    TreeMap 认为比较方法返回 0 的 2 个键是相同的,即使它们彼此不相等,因此您当前的 TreeMap 不能包含两个具有相同音量的键。

    如果您想保持按数量排序并且在您的Map 中仍然有多个相同数量的密钥,请更改您的Comparator 的比较方法以在数量相等时比较Box 的代码.这样它只会在键相等时返回 0。

    Map<Box, String> treeMap = new TreeMap<>((a,b)-> a.volume != b.volume ? Integer.compare(a.volume, b.volume) : a.code.compareTo(b.code));
    

    现在的输出是:

    C:test3
    D:test4
    

    【讨论】:

    • 你的例子会更清楚new TreeMap&lt;&gt;(comparingInt(Box::volume).thenComparing(Box::volume))
    【解决方案2】:

    b3 和 b4 的体积相同,即 0(int 默认值)。

    为了让它起作用,请在比较之前为 Box 体积变量分配一个值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      相关资源
      最近更新 更多