I have a very simple class with only one field member (e.g. String). Is it OK to implement hashCode()
to simply return fieldMember.hashCode()
? Or should I manipulate the field's hash code somehow? Also, if I should manipulate it, why is that?
views:
751answers:
9Yeah, that's pretty standard. And if the class reflects a database row, I just return the primary key.
If fieldMember is a pretty good way to uniquely identify the object, I would say yes.
Joshua Bloch lays out how to properly override equals and hashCode in "Effective Java" Chapter 3.
Ya. It is good programming practice. I normally use:
return var ^ 1;
There are only two real requirements for hashCode
: one, that equals
instances have equal hash codes, and two, that hashCode
runs reasonably fast. The first requirement is the most important one in practice; without it, you could put something into a collection but not find it there. The second is simply a performance issue.
If the hash code algorithm of your field meets the above, then its algorithm also works for your class, if your class equals
also depends solely on whether those fields are equals
.
Multiplying, adding, or xor-ing things will not make it more unique. Mathematically, you'd be applying constant functions to a single variable, which does not increase the number of possible values of the variable.
That sort of technique is useful for combining multiple hashcodes and still keeping the risk of collisions relatively small; it has no bearing whatever on a single hashcode.
If 'fieldMember' variable already implements 'hashCode' function then you can use it directly from your parent class. If 'fieldMember' variable is a custom class instance, then you must implement it correctly by yourself. Read java.lang.Object API documentation as guideline to implement 'hashCode'.
Usually, unless you are using this object as the key for a *HashMap or an element in a *HashSet, hashCode() doesn't need to be overridden.
As someone else mentioned, you should follow the advice in Effective Java. If you override the hashCode() method, you should also be overriding the equals() method. Furthermore, the two methods should be consistent.
To simplify writing good equals() and hashCode() methods, I use EqualsBuilder and HashCodeBuilder from Apache Commons Lang
Here are examples:
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User other = (User) o;
return new EqualsBuilder()
.append(this.getUniqueId(), other.getUniqueId())
.isEquals();
}
public int hashCode() {
return new HashCodeBuilder()
.append(this.getUniqueId())
.toHashCode();
}