【发布时间】:2010-11-15 15:05:36
【问题描述】:
我记得eclipse和idea都有这个模板可以根据属性自动创建对象的hashCode。
如果使用数字和字符串,其中一种策略是这样的。
return stringValue.hashCode() + intValue * 32;
类似的东西。
我手头没有日食或想法,我想创建这样的功能。
编辑
根据答案我创建了这个迷你班
class StringInt {
private final String s;
private final int i;
static StringInt valueOf( String string , int value ) {
return new StringInt( string, value );
}
private StringInt( String string, int value ) {
this.s = string;
this.i = value;
}
public boolean equals( Object o ) {
if( o != null && o instanceof StringInt ){
StringInt other = ( StringInt ) o;
return this.s == other.s && this.i == other.i;
}
return false;
}
public int hashCode() {
return s != null ? s.hashCode() * 37 + i : i;
}
}
此类将用作大型内存映射(> 10k 个元素)的键,我不想每次都迭代它们以查找 String 和 int 是否相同。
谢谢。
ps.. mmh 可能应该是名称 StringIntKey。
【问题讨论】:
-
奥斯卡,我认为这是一堂好课。 hashCode 方法清晰、可靠且高效。如何防止字符串为空?在您的构造函数中,如果 NPE 为空,则抛出一个 NPE。然后你可以删除那些在 equals 和 hashCode 中的空保护。最后,为此类问题保留一份“Effective Java”副本。 Eclipse 和 IDEA 创建的 hashCode 方法就是基于那本书。
-
在你的equals方法中应该比较字符串使用equals而不是==。
标签: java eclipse hash code-generation intellij-idea