您如何在Objects#hash(Object...)
方法中使用hashCode()
?
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});
}
当然在正常情况下,例如使用equals(Object)
方法等等。 Joshua Bloch在他的书中写道如何使用他的规则/配方编写一个好的hashCode()
方法,比如移位等等。
上面的示例不遵循原始数据类型的这些规则...所以我的问题是,是否可以处理像对象(autoboxing)这样的原始数据类型而不是遵循Bloch的配方或使用Apache Commons HashCodeBuilder
?
Objects#hash(Object...)
是在Java 7中引入的,仅调用Arrays.hashCode(Object[])
,因此这个问题也集中在Java 6用户身上。
感谢您的回复/想法/建议!