如何在Objective-C中获得Java String.hashCode()的相同结果?

我一直在http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java上阅读有关String.hashCode()的文档。来自相同字符串的相同结果,但我没有得到任何令人满意的结果。 在Objective-C [NSString hash]中给出了完全不同的结果。

有没有人这样做过?

谢谢

阿尔弗雷德提供的答案是不正确的。 首先,hashCode可以返回负数,因此返回类型应该是有符号整数而不是无符号整数。 其次,charAsciiValue ++已关闭。 在原始Java代码中,数组索引正在递增,而不是unichar。 这是一个测试/工作版本,它是NSString上的一个类别:

- (int)javaHashCode { int h = 0; for (int i = 0; i < (int)self.length; i++) { h = (31 * h) + [self characterAtIndex:i]; } return h; } 

编辑:我最初使用NSInteger,但我遇到了问题。 我相信这是因为机器是64位。 将NSInteger切换为int修复了我的问题。

更新了swift 4的代码

 func javaHashCode(name:String)-> Int{ var nsname = name as! NSString; var h:Int = 0 for (index,value) in name.enumerated(){ h = 31*h + Int(nsname.character(at:index)) } return h } 

我使用维基页面上的数学算法创建了一个模拟Java string.hashCode()结果的高效代码片段: http : //en.wikipedia.org/wiki/Java_hashCode%28%29#The_java.lang.String_hash_function

 + (NSUInteger) hashCodeJavaLike:(NSString *)string { int h = 0; int len = string.length; for (int i = 0; i < len; i++) { //this get the ascii value of the character at position unichar charAsciiValue = [string characterAtIndex: i]; //product sum algorithm over the entire text of the string //http://en.wikipedia.org/wiki/Java_hashCode%28%29#The_java.lang.String_hash_function h = 31*h + (charAsciiValue++); } return h; 

}

希望对某人有所帮助! 请记住,正如Chris所评论的那样,如果重写Java string.hashCode()算法,可能会出现问题。