Ole Ole - 1 year ago 111
Java Question

Should JPA entities return a constant for the hashcode() implementation?

This article suggests a JPA

equals
and
hashcode
implementation that returns
31
always for the
hashcode
. Would this not become a problem when we try to add entitities to a HashMap or HashSet?

In other words if I try insert a two JPA entity instances of type Product like this:

//Load product1 and product2
Set<Product> products = new HashSet<>();
products.add(product1);
products.add(product2);


Will the products
Set
now contain two products even though the
hashcode
for both of these products is the same?

Answer Source

Definitely. See Class HashMap documentation. HashSet is backed by a HashMap, so this applies to HashSet too. See Class HashSet documentation.

To the second question, no. HashMap uses equality to decide whether an entity is equal. It will just be terribly inefficient since the map will degenerate to a linked list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download