JDK-6552529 : (coll) Map.getEntry(key), Map.getKey(key)
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6
  • Priority: P4
  • Status: Open
  • Resolution: Unresolved
  • OS: linux
  • CPU: x86
  • Submitted: 2007-05-02
  • Updated: 2012-10-08
Description
A DESCRIPTION OF THE REQUEST :
I think the only reason this hasn't been implemented before is because it is Too Obvious, so no-one saw the need.

I would like to see public getEntry(Object key) and getKey(Object key) methods added to the Map interface, or at least to the WeakHashMap class.

JUSTIFICATION :
This would be useful because it would allow the application to get hold of the actual object used as the key in the Map given an object which is just equivalent. For a WeakHashMap this can be important, because it provides a way of ensuring that entries do not disappear from the map before the application has completely finished with them, by making everything use the same instance of the key object.

Moreover, it allows a slightly faster method of updating the value of  a mapping. A common code pattern is to use a Map to store instance counts or some similar status information for multiple "things", which needs to be updated multiple times. The normal way to do this is to call Map.get with the "thing", take the value returned, and then call Map.put with an altered value, resulting in two map lookup operations. If a getEntry() method is available, then a single lookup operation can retrieve the Entry, and the setValue method of the Entry can then be used to update the value without having to perform another lookup operation.


CUSTOMER SUBMITTED WORKAROUND :
Currently I have to use a second WeakHashMap mapping from the key objects to a WeakReference holding the key. This allows me to disambiguate the key objects, but it does not provide access to the Entry objects.

Comments
EVALUATION An interesting suggestion. Unlikely to happen, since methods can never be added to Interfaces compatibly. As a practical matter, WeakHashMaps should only be used to store objects with a trivial .equals() method, since the garbage collector uses identity semantics, not value equality.
02-05-2007