Java hash of 2 hashes

hashcode, java

Solution

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`.

Problem

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?

Original source

Related problems