假设我有一个 HashMap<K, V>
和两个 K
类型的对象彼此相等但不是同一个对象,并且映射具有键 k1
的条目.
给定k2
, 我可以引用 k1
仅使用 HashMap
中的方法(没有外部数据结构)以恒定时间执行,即 O(1) 时间复杂度?
在代码中:
K k1, k2;
k1.equals(k2) // true
k1.hashCode() == k2.hashCode() // true
k1 == k2 // false
myMap.put(k1, someValue);
K existingKey = getExistingKey(myMap, k2);
existingKey == k1 // true <- this is the goal
<K> K getExistingKey(HashMap<K, V> map, K k) {
// What impl goes here?
}
我希望使用 java 8 添加的各种方法之一,例如 compute()
“嗅探”lambda 中的现有 key ,但它们都(似乎)将新 key 对象传递给 lambda,而不是现有 key 。
遍历 entrySet()
会找到现有的 key ,但不是在恒定时间内。
我可以使用 Map<K, K>
存储 key ,我可以保持同步,但这并不能回答问题。
最佳答案
你正在寻找类似的东西
Map.Entry<K,V> getEntry(K key)
起初我认为创建一个 HashMap
的自定义子类来返回它会很容易,因为 get(K key)
就是
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
其中 Node
实现了 Map.Entry
。这看起来像:
public class MyHashMap<K,V> extends HashMap<K,V>
{
public MyHashMap() {}
// Other constructors as needed
public Map.Entry<K, V> getEntry(K key)
{
Map.Entry<K, V> e = getNode(hash(key),key);
return e;
}
}
不幸的是,getNode()
和hash()
都是包私有(private)的,因此对子类不可见。
下一步是将类放在 java.util
中,但这在 Java 9 中失败了
The package java.util conflicts with a package accessible from another module: java.base
我觉得你运气不好。
我实际上认为 getEntry()
方法是对 API 的有用补充,您可以考虑提交增强请求。
关于java - 在给定另一个等效键对象的情况下获取映射条目的当前键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47862326/