-
-
Save universal/5336319 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyClass | |
{ | |
public static void main(String args[]) | |
{ | |
System.out.println("Hello World".hashCode()); | |
} | |
} | |
=> -862545276 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* taken from jdk-7 sourcecode */ | |
public String { | |
public int hashCode() { | |
int h = hash; | |
if (h == 0 && count > 0) { | |
int off = offset; | |
char val[] = value; | |
int len = count; | |
for (int i = 0; i < len; i++) { | |
h = 31*h + val[off++]; | |
} | |
hash = h; | |
} | |
return h; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class JavaHashCode | |
attr_accessor :string | |
def initialize(_string) | |
@string = _string | |
end | |
def hashCode | |
sum(parts) | |
end | |
def hashCode2 | |
h = 0 | |
self.string.chars.each do |char| | |
h = (31*h) + char.ord | |
end | |
to_signed_int(h) | |
end | |
private | |
def parts | |
size = self.string.size | |
hash = 0 | |
parts = [] | |
self.string.chars.each_with_index do |ch, i| | |
parts << to_signed_int(ch.ord * 31 ** (size - (i+1))) | |
end | |
parts | |
end | |
def sum(summands) | |
summands.inject(0) {|h, i| | |
to_signed_int(h + i) | |
} | |
end | |
# http://stackoverflow.com/questions/7365868/how-do-i-emulate-integer-overflow-on-a-fixnum-variable - copied from the last anser | |
def to_signed_int(i) | |
if i < -2147483648 | |
i & 0xffffffff | |
elsif i > 2147483647 | |
-(-(i) & 0xffffffff) | |
else | |
i | |
end | |
end | |
end | |
puts JavaHashCode.new("Hello World").hashCode | |
=> -862545276 | |
puts JavaHashCode.new("Hello World").hashCode2 | |
=> -862545276 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment