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.
hashCode(Object o) should be used when you want the hash of a single object, without throwing if the object is null.
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();
“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.)”
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.
Note that the parameter of Objects.hash
is Object...
. This has two main consequences:
this.id
is converted from long
to Long
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With