xyz*_*xyz 6 java collections multikey
我正在尝试实现类似的地图
Map<<key1, key2>, List<value>>
Run Code Online (Sandbox Code Playgroud)
地图应包含2个键,相应的值将是一个列表.如果更改一个键值相等,我想在同一列表中添加记录 例如,考虑以下记录
R1[key1, key2]
R2[key1, null/empty] - Key1 is equal
R3[null/empty, key2] - Key2 is equal
R4[key1, key2] - Key1 and Key2 both are equal.
Run Code Online (Sandbox Code Playgroud)
所有应该插入相同的列表中
Key = <Key1,Key2>
Value = <R1, R2, R3, R4>
Run Code Online (Sandbox Code Playgroud)
我不能使用Guava表或公共MulitKeyMap(不要只为此包含整个库).
我试图实现一个类(我可以用作一个键),它将具有key1和key2作为属性,但实现一个有效的哈希码,不考虑key1和key2似乎有点(或可能很多)棘手
public class Key {
private int key1;
private int key2;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
// Cant include key1 and key2 in hashcode
/* result = prime * result + key1;
result = prime * result + key2;*/
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Key other = (Key) obj;
if(key2 and other.key2 both not blank/null){ // pseudo code
if (key2 == other.key2)
return true;
}
if(key1 and other.key1 both not blank/null){ //pseudo code
if (key1 == other.key1)
return true;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我对所有人使用相同的哈希码,它将起作用,但它会影响性能,因为我有数千条记录.
编辑:
我不能使用嵌套的地图喜欢
Map<key1, Map< key2, List<value>>>
Run Code Online (Sandbox Code Playgroud)
有些记录可能只有一个密钥.
R1[key1, key2] - Have both keys
R2[key1, null/empty] - Key1 is equal
R3[null/empty, key2] - Key1 is missing and key2 is equal
Run Code Online (Sandbox Code Playgroud)
这里R3没有key1,因此无法插入与R1和R2相同的位置
编辑2:
我也希望保持互动秩序.
请改用 TreeMap,这样您就可以为 CustomKey 类使用自定义比较器而不是哈希码。
TreeMap<CustomKey, List<value>> map = new TreeMap<CustomKey, List<value>>(myComparator);
Run Code Online (Sandbox Code Playgroud)
eta:您可以使 CustomKey 类实现 Comparable,而不是创建比较器类
| 归档时间: |
|
| 查看次数: |
18887 次 |
| 最近记录: |