Your hashCode
is not that bad if both user and product create pseudo-random hash-codes. If you are afraid of hash collisions because of bad hashCode implementations in either user
or product
, then multiply one of the source hash codes by a prime number:
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((product == null) ? 0 : product.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
Eclipse builds this very code when selecting Source | Generate hashCode() and equals().
As mentioned by Thilo, you can also simply use Arrays.hashCode(new Object[]{ user, product })
; This call takes care of null
values for user or product and also multiplies the result by 31 - same as the hand written code.
If you are using Google Guava, there is an Objects.hashCode(Object...)
that makes your intent a little bit clearer and uses varargs, but it also only delegates to Arrays.hashCode
.