【发布时间】: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);
}
}
谢谢
【问题讨论】: