How to obtain the same result of Java String.hashC

2019-06-04 06:46发布

I've been reading documentation about String.hashCode() on http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java Trying obtain an identical result from an identical string, but I did not come up with any satisfying results. In Objective-C [NSString hash] gives a totally different result.

Have anyone already done this?

Thanks

3条回答
贪生不怕死
2楼-- · 2019-06-04 07:18

I made an efficient snippet that mimic the Java string.hashCode() result using the math algorithm at the wiki page: 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;

}

hope it help someone! Keep in mind, as commented by Chris, that if the Java string.hashCode() algorithm is rewritten problems may occur.

查看更多
The star\"
3楼-- · 2019-06-04 07:28

The answer provided by Alfred is not correct. First of all, hashCode can return negative, so the return type should be a signed integer and not an unsigned integer. Secondly, the charAsciiValue++ is off. In the original Java code, an array index is being incremented, not a unichar. Here is a tested/working version that's a category on NSString:

- (int)javaHashCode
{
    int h = 0;

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

    return h;
}

Edit: I originally used NSInteger, but I ran into issues with it. I believe it was due to the machine being 64 bit. Switching NSInteger to int fixed my issue.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-06-04 07:37

Updated code for 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 
} 
查看更多
登录 后发表回答