How to get a key object from the map?

Take two instances of the same class A, called foo and bar, where:

foo != bar
foo.equals(bar) == true

In other words, foo and bar are different instances, but with the same hash code. Now take an instance Map<A,B>called "map", where foo is the key on the map. Is it possible to get foo from the map using the panel? I am currently repeating a set of keys and comparing each key, but is there a faster way ? It seems that there are no methods in Map to extract the keys.

I am ready to try any data structure that implements Map or can work like a map.

Why do I want to do this? I try to avoid unnecessary cases than necessary. As soon as I find foo, I can free the bar.

Thanks in advance...

+4
source share
5 answers

You can use Apache Commons Collections ™ . It has bidirectional cards BidiMap.
They are maps where a key can search for a value, and a value can search for a key with equal ease.

BidiMap bidi = new TreeBidiMap();
bidi.put("SIX", "6");
bidi.get("SIX");  // returns "6"
bidi.getKey("6");  // returns "SIX"
bidi.removeValue("6");  // removes the mapping
BidiMap inverse = bidi.inverseBidiMap();  // returns a map with keys and values swapped

see also

+1
source

HashMap does have a method for retrieving a record, but it is a closed package. I'm not quite sure why this is not public, to be honest. I don’t think he reveals anything. You can, of course, call it reflection.

Map<String, String> map = new HashMap<String, String>();
map.put(new String("hello"), "world!");

Method method = (
    HashMap.class.getDeclaredMethod("getEntry", Object.class)
);
method.setAccessible(true);

@SuppressWarnings("unchecked")
Map.Entry<String, String> entry = (Map.Entry<String, String>)(
    method.invoke(map, new String("hello"))
);

System.out.println(entry.toString().replace("=", " ")); // hello world

Reflection probably makes it not useful in the scenario you described, but I think it might be useful to others. I would not recommend using it.

+1

. , (, ). :

  • map.get(key) == null,
  • map.get(key) == firstObjectAllocated
+1

HashMap

: foo.hashCode() == bar.hashCode() foo.equals(bar)

, foo by map.get(bar)


: , , , -. , , -, .

HashMap<K,V> map = new HashMap<K,V>();
HashMap<K,K> cacheKeys = new HashMap<K,K>();
cacheKeys.put(foo,foo);
map.put(foo,value);

//now you have var bar; you could retrieve the cached key
bar = cacheKeys.get(bar);//this will make bar = foo; the real bar will be gc
//then get the value 
val = map.get(bar);
0

.

   Iterator<A> mapKeyIterator=map.keySet().iterator();
    while (mapKeyIterator.hasNext()){
        A key;
        if((key=mapKeyIterator.next()).equals(bar)) {
            return key;
        }
    }
0

Source: https://habr.com/ru/post/1528031/


All Articles