java - 用值组合 int 键
问题描述
我需要将自定义对象作为值存储在字典中,例如具有两个复合整数键的 datastrukturer。(复合 ID)
我尝试使用数组作为键,但两者都不起作用,因为我猜这只是指向该数组的指针,用作键
如果我可以使用就好了
store.put([12,43],myObject);
store.get([12,43]);
解决方案
Anint[]
不起作用,因为(请参阅Java 中的 equals vs Arrays.equals):
public static void main(String[] args) throws Exception {
int[] one = new int[] { 1, 2, 3 };
int[] two = new int[] { 1, 2, 3 };
System.out.println(one.equals(two)); // <<--- yields false
}
但是,如果:
Map<List<Integer>, Object> store = new HashMap<>();
那么你也能:
store.put(Arrays.asList(12, 43), myObject);
myObject == store.get(Arrays.asList(12, 43));
或者可能更多 OO - 创建StoreKey
简单封装的类型List
:
public final class StoreKey {
private List<Integer> keyParts;
public static StoreKey of(int... is) {
return new StoreKey(IntStream.of(is)
.boxed()
.collect(Collectors.toList()));
}
public StoreKey(List<Integer> keyParts) {
this.keyParts = keyParts;
}
@Override
public int hashCode() {
return keyParts.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof StoreKey)) {
return false;
}
return this.keyParts.equals(((StoreKey) obj).keyParts);
}
}
接着:
Map<StoreKey, Object> store = new HashMap<>();
store.put(StoreKey.of(12, 43), myObject);
最后,我们可以看到这将作为一个关键,因为:
public static void main(String[] args) throws Exception {
StoreKey one = StoreKey.of(1, 2, 3);
StoreKey two = StoreKey.of(1, 2, 3);
System.out.println(one.equals(two)); // <<--- yields true
}
推荐阅读
- amazon-web-services - Azure 中的签名 URL
- javascript - 使用 $(document).ready(function() 更改标签的文本
- javascript - 为什么服务器上的“窗口”编码问题上的“atob”而不是本地的(laravel 代客)?
- php - 文件上传无法插入mysqli数据库
- android - 使用 ViewPager 的自动滑块图像
- javascript - 解释一系列箭头运算符
- python - Python:在散点图中查找多条线性趋势线
- spring - CSS + Thymleaf - CSS 不反映在页面上
- html - 输入表单中的自动数字空间
- sql - 计算一个案例中的案例数量