我記得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