我记得 Eclipse 和 IntelliJ IDEA 有自动生成对象 hashCode 的模板,根据其属性值生成。
如果使用一个数字和一个字符串作为属性值,则一种常见的策略如下:
return stringValue.hashCode() + intValue * 32;
或类似于那样的东西。
我手头没有Eclipse或Idea,我想创建这样的功能。
编辑
根据答案,我创建了这个迷你类。
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 元素)。我不想每次迭代查找字符串和整数是否相同。
谢谢。
PS.. 可能应该将其命名为StringIntKey。