如何在Objective-C中获得Java String.hashCode()的相同结果? [英] How to obtain the same result of Java String.hashCode() in Objective-C?

查看:115
本文介绍了如何在Objective-C中获得Java String.hashCode()的相同结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



有没有人已经完成了这个?



谢谢

解决方案

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

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


}

return h;编辑:我最初使用NSInteger,但我碰到了它的问题。我相信这是由于该机器是64位。将NSInteger切换到int修复了我的问题。


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

解决方案

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.

这篇关于如何在Objective-C中获得Java String.hashCode()的相同结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆