java – 从string和int创建哈希

我记得
eclipse和想法有这个模板根据自己的属性自动创建一个对象的hashCode.

使用数字和字符串的策略之一就是这样.

return stringValue.hashCode() + intValue * 32;

不好意思

我没有,也没有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可能应该是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

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。