Java字符串上hashCode()的一致性 [英] Consistency of hashCode() on a Java string

查看:65
本文介绍了Java字符串上hashCode()的一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java String的hashCode值计算为( String.hashCode()):

The hashCode value of a Java String is computed as (String.hashCode()):

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

是否有任何情况(比如JVM版本,供应商等),下面的表达式将评估为false?

Are there any circumstances (say JVM version, vendor, etc.) under which the following expression will evaluate to false?

boolean expression = "This is a Java string".hashCode() == 586653468

< b>更新#1:如果您声称答案是是,有这种情况 - 那么请举一个具体的例子,说明这是一个Java字符串.hashCode()!= 586653468。尝试尽可能具体/具体。

Update #1: If you claim that the answer is "yes, there are such circumstances" - then please give a concrete example of when "This is a Java string".hashCode() != 586653468. Try to be as specific/concrete as possible.

更新#2:我们都知道依赖hashCode()的实现细节很糟糕一般来说。但是,我正在特别谈论String.hashCode() - 所以请将答案集中在String.hashCode()上。 Object.hashCode()在这个问题的上下文中完全不相关。

Update #2: We all know that relying on the implementation details of hashCode() is bad in general. However, I'm talking specifically about String.hashCode() - so please keep the answer focused to String.hashCode(). Object.hashCode() is totally irrelevant in the context of this question.

推荐答案

我可以看到早在Java的文档1.2。

I can see that documentation as far back as Java 1.2.

虽然一般确实不应该依赖哈希码实现保持不变,但现在记录的行为 java.lang.String ,所以更改它会被视为破坏现有合约。

While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String, so changing it would count as breaking existing contracts.

只要有可能,你不应该依赖哈希码在版本之间保持不变等 - 但在我看来 java.lang.String 是一个特例,因为算法已经了指定...当然,只要您愿意在指定算法之前放弃与版本的兼容性。

Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.

这篇关于Java字符串上hashCode()的一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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