gpt4 book ai didi

java - 从字符串和整数创建散列

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:22 24 4
gpt4 key购买 nike

我记得eclipse和idea有这个模板可以根据对象的属性自动创建对象的hashCode。

如果使用数字和字符串,其中一种策略是这样的。

  return stringValue.hashCode() + intValue * 32;

Ooor 类似的东西。

我手头没有 eclipse 或想法,我想创建这样的功能。

编辑

根据我创建这个小类的答案

    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 可能它应该是 names StringIntKey。

最佳答案

使用 Apache Commons HashcodeBuilder:

public int hashCode() {
new HashCodeBuilder(17, 37).
append(myString).
append(myInt);
}

链接在这里: http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/builder/HashCodeBuilder.html

在这里:

http://www.koders.com/java/fidCE4E86F23847AE93909CE105394B668DDB0F491A.aspx

关于java - 从字符串和整数创建散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1209633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com