Suppose you have this code:
Map map = new HashMap();
Foo foo = new Foo();
Bar bar = new Bar();
map.put(foo, bar);
Bar barReturned = map.get(foo);
Does Java require that barReturned == bar? That is, does Java require that barReturned be the same instance as bar? If not, what semantics are expected?
The Javadoc suggests that barReturned == bar must be true, but I'm not 100% sure:
V get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)
If this map permits null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.
Parameters:
key - the key whose associated value is to be returned
Returns:
THE VALUE TO WHICH THE SPECIFIED KEY IS MAPPED, or null if this map contains no mapping for the key
(Emphasis mine)
Edit: I understand that the implementations of Map that come bundled with the standard library adhere to the barReturned == bar semantics. What I want to know is whether or not this behavior is required as per the documentation. For example, must I also adhere to these semantics if I write my own class that implements Map?
解决方案
If you are asking whether you can break that relation, i think the answer is "yes". for instance, if you were implementing a Map which acted like a persistent cache, a specific value may be written to disk if not used in a while, then reloaded later. you will not have reference equality in that situation, but that's okay. obviously, you would want to document any deviations from standard behavior, but i don't think this is out of the realm of a reasonable usage of a Map.