Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Objects.hash() or own hashCode() implementation?

Tags:

java

hash

I have recently discovered the Objects.hash() method.

My first thought was, that this tidies up your hashCode() implementation a lot. See the following example:

@Override //traditional public int hashCode() {     int hash = 5;     hash = 67 * hash + (int)(this.id ^ (this.id >>> 32));     hash = 67 * hash + (int)(this.timestamp ^ (this.timestamp >>> 32));     hash = 67 * hash + Objects.hashCode(this.severity);     hash = 67 * hash + Objects.hashCode(this.thread);     hash = 67 * hash + Objects.hashCode(this.classPath);     hash = 67 * hash + Objects.hashCode(this.message);     return hash; }  @Override //lazy public int hashCode() {     return Objects.hash(id, timestamp, severity, thread, classPath, message); } 

Although I have to say that this seems too good to be true. Also I've never seen this usage.

Are there any downsides of using Objects.hash() compared to implementing your own hash code? When would I choose each of those approaches?

Update

Although this topic is marked as resolved, feel free to keep posting answers that provide new information and concerns.

like image 808
Herr Derb Avatar asked Aug 23 '17 06:08

Herr Derb


People also ask

Should I use objects hash?

hashCode(Object o) should be used when you want the hash of a single object, without throwing if the object is null.

How is the hashCode implemented in object Java?

Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode();

Where hashCode method is implemented?

“As much as is reasonably practical, the hashCode() method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)”

What is the default implementation of hashCode method in object class?

Uses of hashCode() and equals() Methods Its default implementation simply checks the object references of two objects to verify their equality. By default, two objects are equal if and only if they are refer to the same memory location. Most Java classes override this method to provide their own comparison logic.


1 Answers

Note that the parameter of Objects.hash is Object.... This has two main consequences:

  • Primitive values used in the hash code calculation have to be boxed, e.g. this.id is converted from long to Long.
  • An Object[] has to be created to invoke the method.

The cost of creating of these "unnecessary" objects may add up if hashCode is called frequently.

like image 145
Andy Turner Avatar answered Oct 02 '22 09:10

Andy Turner