Java 实现 (key1, key2, value) 数据结构
可以使用 Java 中的 Map 接口来实现 (key1, key2, value) 这种数据结构。
例如,可以使用 HashMap 类来创建一个存储键值对的 Map 对象,其中键类型为 key1 和 key2 的组合,值类型为 value。
示例代码如下:
import java.util.HashMap;
import java.util.Map;
public class MyDataStructure {
private Map<KeyPair, Value> data;
public MyDataStructure() {
data = new HashMap<>();
}
public void put(Key1 key1, Key2 key2, Value value) {
KeyPair keyPair = new KeyPair(key1, key2);
data.put(keyPair, value);
}
public Value get(Key1 key1, Key2 key2) {
KeyPair keyPair = new KeyPair(key1, key2);
return data.get(keyPair);
}
private class KeyPair {
private Key1 key1;
private Key2 key2;
public KeyPair(Key1 key1, Key2 key2) {
this.key1 = key1;
this.key2 = key2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key1 == null) ? 0 : key1.hashCode());
result = prime * result + ((key2 == null) ? 0 : key2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
KeyPair other = (KeyPair) obj;
if (key1 == null) {
if (other.key1 != null)
return false;
} else if (!key1.equals(other.key1))
return false;
if (key2 == null) {
if (other.key2 != null)
return false;
} else if (!key2.equals(other.key2))
return false;
return true;
}
}
}
在这个例子中,KeyPair 类作为 Map 的键类型,包含两个键值对 key1 和 key2。hashCode() 和 equals() 方法被重写,以确保相同的键值对被视为相同的对象。
原文地址: https://www.cveoy.top/t/topic/mlIJ 著作权归作者所有。请勿转载和采集!