0

I have a project with many bean classes like ItemBean:

public class ItemBean
{
    private String name;
    private int id;


    getters/setters...
}

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 stackoverflow questions and this tutorial, but they seem overly general whereas I'm looking for best practices for simple bean classes.

I came up with this method:

  • Uses caching
  • Uses all attributes that are involved in the equals method of ItemBean
  • Uses the 17/31 'magical number' primes as described in the other stackoverflow question.

Implemented method:

public final int hashCode()
{
    if (cachedHashCode == 0)
    {
        int result = 17;
        result = 31 * (result + id);
        cachedHashCode = 31 * (result + name.hashCode());
    }

    return cachedHashCode;
}

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?

Community
  • 1
  • 1
user1884155
  • 3,616
  • 4
  • 55
  • 108

1 Answers1

1

From the JavaDoc of Object.hashCode():

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

This can be achieved by using all members in hashCode that are used in equals and vice-versa.

The alorightms described in What is a best practice of writing hash function in java? are worth following.

I would not worry about performance. ^ is a very basic operator that is and can be optimized by the JVM.

Community
  • 1
  • 1