Bud*_*dhi 3 java hashmap treemap
我的目标是使用 TreeMap 使 Box 键对象按 Box.volume 属性排序,同时能够放置由 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);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
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));
Run Code Online (Sandbox Code Playgroud)
现在输出是:
C:test3
D:test4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |