我记得eclipse和想法有这个模板来根据它的属性自动创建一个对象的hashCode。从字符串和int创建哈希
如果使用数字和字符串的策略之一是这样的。
return stringValue.hashCode() + intValue * 32;
这种东西就是这样。
我没有,也没有日食或想法在手边,我想创建这样的功能。
EDIT
基于I创建这个微型类
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方法清晰,可靠且高效。 怎么样防止字符串为空?在你的构造函数中,如果它是null,则抛出一个NPE。然后你可以在equals和hashCode中删除那些空警号。 最后,为这样的问题保留一份“Effective Java”的副本。 Eclipse和IDEA创建的hashCode方法基于该书。 – 2009-07-31 07:23:56
在你的equals方法中,应该比较字符串use equals而不是==。 – 2009-07-31 15:09:12