Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you do the <code>hashCode</code> and <code>equals</code> based on the <code>foo</code> (which is what you indicate you are doing) then in your example <code>A</code> and <code>B</code> would end up in the same bucket in the hashmap.<br> As a result <code>getBar(A,myMap);</code> would return <code>5.0</code> because that is what you put in the map- <code>B</code>.<br> I mean you can search for <code>B</code> using <code>A</code> but then each <code>put</code> would replace the previous one and I am not sure from your OP what your actual requirement is </p> <p>Update: </p> <pre><code>Double getBar(MyType type, Map&lt;MyType,Double&gt; map){ if(map.containsKey(type)){ for(MyType k:map.keySet()){ if(k.equals(type)){ return k.bar; } } } return -1.0; } </code></pre> <p><strong>Update 2:</strong><br> It seems that what you need is a way to access the keys in your <code>Map</code> directly. You could use do the following:<br> Define: </p> <pre><code>class Holder{ MyType type; Double value; } </code></pre> <p>and have <code>HashMap&lt;MyType,Holder&gt;</code> instead. So in your method that does the calculation you update the map to add the result in the <code>Holder</code> object where you also store the <code>type</code>. I.e. instead of <code>myMap.put(B,5.0);</code> you do: <code>myMap.put(B,new Holder(B,5.0));</code></p> <p>So you will have: </p> <pre><code>Double getBar(MyType type, Map&lt;MyType,Holder&gt; map){ return map.get(type).type.bar; } </code></pre> <p>You have extra space requirement for storing the <code>type</code> as part of the value of the map as well but you will have gotten rid of the looping to actually find the <code>type</code> as it is now</p>
 

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