How to obtain the same result of Java String.hashCode() in Objective-C?

99封情书 提交于 2019-12-08 04:36:27

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.

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 
} 

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!