title: Strange Java HashMap behavior - can't find matching object
body: <p>I've been encountering some strange behavior when trying to find a key inside a <code>java.util.HashMap</code>, and I guess I'm missing something. The code segment is basically:</p>
  
  <pre><code>HashMap&lt;Key, Value&gt; data = ...
  Key k1 = ...
  
  Value v = data.get(k1);
  boolean bool1 = data.containsKey(k1);
  for (Key k2 : data.keySet()) {
      boolean bool2 = k1.equals(k2);
      boolean bool3 = k2.equals(k1);
      boolean bool4 = k1.hashCode() == k2.hashCode();
      break;
  }
  </code></pre>
  
  <p>That strange for loop is there because for a <strong>specific execution</strong> I happen to know that <code>data</code> contains only one item at this point and it is <code>k1</code>, and indeed <code>bool2</code>, <code>bool3</code> and <code>bool4</code> will be evaluated to <code>true</code> in that execution. <code>bool1</code>, however, will be evaluated to <code>false</code>, and <code>v</code> will be null.</p>
  
  <p>Now, this is part of a bigger program - I could not reproduce the error on a smaller sample - but still it seems to me that <em>no matter what the rest of the program does, this behavior should never happen.</em></p>
  
  <p><strong>EDIT:</strong> I have manually verified that the hash code does <em>not</em> change between the time the object was inserted to the map and the time it was queried. I'll keep checking this venue, but is there any other option?</p>