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?