What do you think about using Objects#hash(Object...) in a hashCode() method?
int a = 1;
boolean b = true;
Date c = new Date();
String d = "1234";
Object e = new ch.example.blabla.Foo();
// Java 7
public int hashCode() {
return Objects.hash(a, b, c, d, e);
}
// or using Java 6
public int hashCode() {
return Arrays.hashCode(new Object[] {a, b, c, d, e});
}
Of course under normal circumstances such as having an equals(Object) method too and so on. Joshua Bloch writes in his book how to write a good hashCode() method using his rules/recipe such as shifting bits and so on.
Above example does not follow these rules for primitive datatypes… so my question is, is it ok to handle primitive datatypes like objects (autoboxing) instead of following Bloch’s recipe or using Apache Commons HashCodeBuilder?
Objects#hash(Object...) was introduced in Java 7 and invokes only Arrays.hashCode(Object[]), so this question is also focused to Java 6 users.
Thank you for your responses/ideas/suggestions!
I really don’t understand when older questions are getting closed as a duplicate because of newer ones.
However, there is a question with better answers here:
Wrapper classes like
Integer,DoubleandBooleando indeed implement the rules which are described in Effective Java of Joshua Bloch. Thank you to Marko Topolnik for highlighting that out.He’s also mentioning a downside which could lead into performance issues. However, Jörn Horstmann assumes that this might be optimized by mordern JVMs.
We’re going with this approach (
Objects.hash(a, b, c)) since it’s way more readable than writing our ownhashCode()method. And if really necessary (if we run into performance issues) we do implement primitive hash code by ourselves.Marko, Jörn, thank you for your comments. If you’re going to write an answer, I’ll change the accepted answer to the best answer.