gpt4 book ai didi

java - 测试字符串的 hashCode

转载 作者:行者123 更新时间:2023-12-02 08:34:36 24 4
gpt4 key购买 nike

我正在编写如下所示的代码:

String s1=new String("hi");
System.out.println(s1.hashCode());
String s2=new String("hi");
System.out.println(s2.hashCode());
String s3=s1.intern();
String s4=s2.intern();
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());

当我运行代码时,所有变量都会打印相同的哈希码:

3329
3329
3329
3329

上述代码的输出是否正确?

最佳答案

是的,这是正确的输出。 The hashCode of String基于字符串的内容(以非常具体的方式,记录在上面链接的文档中)。

由于 s1s2s3s4 都具有相同的内容(“hi”) ,它们都返回相同的 hashCode。

这实际上是必需的,因为a.equals(b)返回true的对象是必需返回的a.hashCode()b.hashCode() 的值相同。

请注意,相反的情况(即“具有相同哈希码的对象必须相等”)是不正确的,并且一般情况下甚至无法完成(简单地考虑有更多可能) String 值大于 int 值,请参阅 the pigeonhole principle )。

关于java - 测试字符串的 hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13723113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com