Java hash of 2 hashes

I have two lists of objects, users and products.

users have their own products, and each product is associated with 1 user

but the product type may be multiple and belong to individual 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 create an identifier for each unique (user + product)

Perhaps this is not a good idea.

user.hashCode() + product.hashCode() 

What could be a good way?

+6
source share
3 answers

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 .

+7
source

You can let Apache Commons HashCodeBuilder do the job for you.

It allows you to write something like

 return new HashCodeBuilder(17, 37). append(user). append(product). toHashCode(); 
+4
source

A common solution is to multiply the first hash with a prime number and then add a second hash.

+1
source

Source: https://habr.com/ru/post/913713/


All Articles