Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen a value is added via Map.put(K, V), must the same instance be returned via Map.get(K)?
    primarykey
    data
    text
    <p>Suppose you have this code:</p> <pre><code>Map&lt;Foo, Bar&gt; map = new HashMap&lt;Foo, Bar&gt;(); Foo foo = new Foo(); Bar bar = new Bar(); map.put(foo, bar); Bar barReturned = map.get(foo); </code></pre> <p>Does Java require that <code>barReturned == bar</code>? That is, does Java <em>require</em> that <code>barReturned</code> be <em>the same instance</em> as <code>bar</code>? If not, what semantics are expected?</p> <p>The <a href="http://download.oracle.com/javase/6/docs/api/java/util/Map.html" rel="nofollow">Javadoc</a> suggests that <code>barReturned == bar</code> must be true, but I'm not 100% sure:</p> <blockquote> <p><strong><code>V get(Object key)</code></strong></p> <p>Returns the value to which the specified key is mapped, or <code>null</code> if this map contains no mapping for the key.</p> <p>More formally, if this map contains a mapping from a key <code>k</code> to a value <code>v</code> such that <code>(key==null ? k==null : key.equals(k))</code>, then this method returns <code>v</code>; otherwise it returns <code>null</code>. (There can be at most one such mapping.)</p> <p>If this map permits <code>null</code> values, then a return value of null does not <em>necessarily</em> indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to <code>null</code>. The containsKey operation may be used to distinguish these two cases.</p> <p><strong>Parameters:</strong></p> <p><code>key</code> - the key whose associated value is to be returned</p> <p><strong>Returns:</strong></p> <p><em><strong>THE VALUE TO WHICH THE SPECIFIED KEY IS MAPPED</em></strong>, or <code>null</code> if this map contains no mapping for the key</p> </blockquote> <p>(Emphasis mine)</p> <p><strong>Edit:</strong> I understand that the implementations of <code>Map</code> that come bundled with the standard library adhere to the <code>barReturned == bar</code> semantics. What I want to know is whether or not this behavior is <strong>required</strong> as per the documentation. For example, must I also adhere to these semantics if I write my own class that implements <code>Map</code>?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload