从Java中的HashMap中获取密钥对象



我想在Java的HashMap中检索键的原始对象,最好的方法是什么?

例如

HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Integer keyObj = new Integer(10);
Integer valueObj = new Integer(100);
// And add maybe 1 million other key value pairs here
//... later in the code, if I want to retrieve the valueObj, given the value of a key to be 10
Integer retrievedValueObj = map.get(10);
//is there a way to retrieve the original keyObj object with value 10 from map?

基本上,用户可以在这里查询任何键值,只为键对象,10 只是一个示例。一些评论说,"你已经有了x对象,你为什么要得到它?嗯,这就像说"你已经有了值对象,你为什么要得到它?这就是HashMap数据结构,存储和检索的目的。

检索

值对象很容易,但似乎没有多少人知道如何检索键对象。好像很多人不明白我为什么要达到10的目标,问为什么?为什么不只值 10。这只是一个大大简化的模型。

好吧,让我给出一点背景。keyObj 是另一个数据结构中的数据,我需要这个原始键对象的确切引用。比如说,有一个包含所有键值的链表,如果我想删除链表中的特定节点。

我不仅对值"10"感兴趣,还对内存位置感兴趣,即在 Java 中对该"10"对象的引用。内存中可能有很多"10"。但那个确切的对象是我想检索的。

下面的迭代器方法答案给出了 O(n) 方法。但我正在寻找的是给定键值的键 OBJECT 的 O(1) 检索。

我能想到的一种方法是将键对象也存储在值中,例如

class KeyAndValue {
     public Integer key;
     public Integer value;
     public KeyAndValue(Integer key, Integer value) {
         this.key = key;
         this.value = value;
     }
}
map<Integer, keyAndValueL> map = new map<Integer, keyAndValueL>();
Integer x = new Integer(10);
map.add(x, new KeyAndValue(x, 100));
//then I can retrieve the reference of x, given value of key 10
Integer newKeyObj = map.get(10).key;

但是这种方法会占用更多内存,对我来说就像是一种黑客攻击。我想知道Java中是否有更优雅的方式。

一个类似但更通用的方法是将"键+值"存储为条目,而不是将封装存储在另一个类中。例:

    Map<Integer, Entry<Integer, Integer>> map = new HashMap<Integer, Entry<Integer, Integer>>();
    Integer x = new Integer(10);
    map.put(x, new AbstractMap.SimpleEntry<Integer, Integer>(x, 100));
    //then I can retrieve the reference of x, given value of key 10
    Entry<Integer, Integer> keyObj = map.get(10);

试试这个

        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        Integer keyObj = new Integer(10);
        Integer valueObj = new Integer(100);
        map.put(keyObj, valueObj);
        Set<Integer> keys = map.keySet();
        Iterator<Integer> iterator = keys.iterator();
        while(iterator.hasNext()){
            Integer x = iterator.next();
            if(map.get(x) == 100)
                System.out.println("key is "+ x);
        }

您可以将键+值对象"作为值"存储,正如您在问题中提到的。

您正在实现的是蝇量级模式的变体。

使用每个托管对象的映射到自身最容易实现这一点:

Map<T, T> cache = new HashMap<>();

对于您遇到的每个对象:

T obj; // comes from somewhere
obj = cache.computeIfAbsent(obj, v -> obj); // reuse, or add to cache if not found

这具有 O(1) 时间复杂度,并且对于如此管理的每个对象,只使用一个额外的对象引用。

最新更新