I want to generate, in Ruby, the same hash code returned by Java's String.hashCode method. What approach would be most elegant? Java's String hashCode implementation is described here: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#hashCode%28%29
-
Have you arrived at any implementation of your own? It would be worth knowing your ideas to suggest the better way :)Kashyap– Kashyap2014-03-30 04:33:06 +00:00Commented Mar 30, 2014 at 4:33
-
The inconvenient part is simulating the int arithmetic of Java since Ruby promotes Fixnum to Bignum.fooledbyprimes– fooledbyprimes2014-03-30 05:14:04 +00:00Commented Mar 30, 2014 at 5:14
-
Any updates or anything my implementation is missing ?bsd– bsd2014-04-02 13:14:38 +00:00Commented Apr 2, 2014 at 13:14
-
I'm looking for full mimic of Java behavior. Thanks!fooledbyprimes– fooledbyprimes2014-04-17 18:43:17 +00:00Commented Apr 17, 2014 at 18:43
Add a comment
|
3 Answers
Here is a simple implementation.
def jhash(str)
result = 0
mul = 1
max_mod = 2**31 - 1
str.chars.reverse_each do |c|
result += mul * c.ord
result %= max_mod
mul *= 31
end
result
end
And some sample runs
jhash("aa")
3104
jhash("")
0
jhash("polygenelubricants") #Java returns -2147483648
1283535072
Note that the java implementation returns a int which is 32 bits wide(31 bits for unsigned). The Java hashcode implementation may also return negative values. This implementation will not mimic java's negative hashcode behaviour. Instead it will return a whole number between 0 and 2**31-1(Integer.MAX_VALUE)