Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create hash from string and int

I remember eclipse and idea have this template to automatically create an object's hashCode based on its attributes.

One of the strategies if a number and a string is used is something like this.

  return stringValue.hashCode() + intValue * 32;

Ooor something like that.

I don't have nor eclipse or idea at hand and I would like to create such function.

EDIT

Based on the answers I create this mini-class

    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;
        }
    }

This class is to be used as key for a large memory map ( > 10k elements ) I don't want to iterate them each time to find if the String and the int are the same.

Thank you.

ps.. mmh probably it should be names StringIntKey.

like image 612
OscarRyz Avatar asked Jul 30 '09 21:07

OscarRyz


2 Answers

Use the Apache Commons HashcodeBuilder:

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

Link here: http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/builder/HashCodeBuilder.html

And here:

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

like image 95
Jon Avatar answered Nov 05 '22 07:11

Jon


Eclipse always does roughly the same hashing function, here's an example for a class with an in and String as fields

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + this.interger;
        result = prime * result + ((this.string == null) ? 0 : this.string.hashCode());
        return result;
    }

They always pick 31 as the prime, and then multiple by build in hash functions or the value if its a primitive. Something like this wouldn't be hard to create as a method.

     public int hashCode(Object ... things) {
         final int prime = 31;
         int result = 1;
         for(Object thing : things) {
             result = prime * result + thing.hashCode();
         }
         return result;
     }
like image 22
Patrick Auld Avatar answered Nov 05 '22 07:11

Patrick Auld