I’m having two lists of objects, users and products
users own products, and each products is associated to 1 user
but a product type can be multiple and be owned by separate users
- users: Ed, Rob
- products: Coca, Sprites(1), Sprites(2), Beer
- Ed has Coca and Sprites(1), Rob Sprites (2) and Beer
I need to generate an id for each unique (user+product)
It’s probably not a good idea to do
user.hashCode() + product.hashCode()
What could be a good way to proceed?
Your
hashCodeis 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 eitheruserorproduct, then multiply one of the source hash codes by a prime number: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 ofnullvalues 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 toArrays.hashCode.