title: Hash function for Bean classes in Java
body: <p>I have a project with many bean classes like ItemBean:</p>
  
  <pre><code>public class ItemBean
  {
      private String name;
      private int id;
  
  
      getters/setters...
  }
  </code></pre>
  
  <p>I wrote a custom equals method because two items should be treated as equal if they have the same id and name, regardless of whether they're the same object in memory or not. I'm now looking into writing a custom hashCode() function. I looked at other <a href="https://stackoverflow.com/questions/2738886/what-is-a-best-practice-of-writing-hash-function-in-java">stackoverflow questions</a> and <a href="http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml" rel="nofollow noreferrer">this tutorial</a>, but they seem overly general whereas I'm looking for best practices for simple bean classes.</p>
  
  <p>I came up with this method:</p>
  
  <ul>
  <li>Uses caching</li>
  <li>Uses all attributes that are involved in the equals method of ItemBean</li>
  <li>Uses the 17/31 'magical number' primes as described in the other stackoverflow question.</li>
  </ul>
  
  <p>Implemented method:</p>
  
  <pre><code>public final int hashCode()
  {
      if (cachedHashCode == 0)
      {
          int result = 17;
          result = 31 * (result + id);
          cachedHashCode = 31 * (result + name.hashCode());
      }
  
      return cachedHashCode;
  }
  </code></pre>
  
  <p>Is is good practice to base your hashcode method like this on all the attributes of a class that make it unique? If not, what are disadvantages of this method and what are better alternatives? If one my bean classes has 10 attributes instead of only 2, is XOR'ing ten attributes a costly operation that should be avoided or not?</p>