title: java HashMap key swap during get()
body: <p>In a usage case, I have a HashMap which contains 1 entry and the key is A. I need to call get() with key B many many times. A equals() to B but A and B are not the same object. The Key  contains a long array so its equals() is expensive. I am trying to improve the performance for this map checking operation. I know there are proper ways to address the performance issue. However, I am considering a hack which is the most expedient.</p>
  
  <p>The following is from HashMap.java:</p>
  
  <pre><code>    public V get(Object key) {
          if (key == null)
              return getForNullKey();
          int hash = hash(key.hashCode());
          for (Entry&lt;K,V&gt; e = table[indexFor(hash, table.length)];
               e != null;
               e = e.next) {
              Object k;
              if (e.hash == hash &amp;&amp; ((k = e.key) == key || key.equals(k)))
                  return e.value;
          }
          return null;
      }
  </code></pre>
  
  <p>if i change the if block in the for loop to:</p>
  
  <pre><code>        if (e.hash == hash) {
              if (e.key == key) {
                  return e.value; 
              } else if (e.key.equals(key)) {
                  e.key = (K) key;
                  return e.value;
              }
          }
  </code></pre>
  
  <p>I think it will help the performance a lot. The first time I call get() with key B, B's equals() will be called. For the rest of times, B will be == to the key in the map thus saves the equals() call.</p>
  
  <p>However, it is not possible to just extend HashMap and override get() since HashMap.field is package protected and Entry.key is final.</p>
  
  <p>Questions:</p>
  
  <ol>
  <li><p>Will this scheme work?</p></li>
  <li><p>Copying HashMap.java and its related code just to change one method is not very appealing. What is the best way to implement this hack?</p></li>
  </ol>
  
  <p>Thanks!</p>