Your hashCode
not so bad if the user and the product create pseudo-random hash codes. If you are afraid of hash collisions due to unsuccessful hashCode implementations in 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 creates this code when choosing Source | Generate hashCode () and equals ().
As mentioned in Thilo, you can also just use Arrays.hashCode(new Object[]{ user, product })
; This call takes into account null
values ββfor the user or product, and also multiplies the result by 31 - the same as the manual code. If you use Google Guava, there is Objects.hashCode(Object...)
which makes your intention a little clearer and uses varargs, but it also delegates only Arrays.hashCode
.
source share