Herr Derb Herr Derb - 2 months ago 12
Java Question

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

I recently have discovered the

method.

My first thought was, that this tidies up your
hashCode()
implementation a lot. See 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 to good to be true. Also I'd never had seen this usage.

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

Update

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

Answer Source

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.