【问题标题】:How a string present in a string pool and a string present in a heap outside stringpool have same hashCode? [duplicate]字符串池中的字符串和字符串池外的堆中的字符串如何具有相同的 hashCode? [复制]
【发布时间】:2019-01-12 19:03:01
【问题描述】:

考虑下面给出的一段代码。 我想知道字符串池“s1”或“s2”中的字符串如何与堆中的字符串“s3”具有相同的hashCode,但在字符串池之外。

class Test{
public static void main(String[] args) {
    String st1 = "Shiva";
    String st2 = "Shiva";
    String st3 = new String("Shiva");
    System.out.println(st1 == st2);
    System.out.println(st1 == st3);
    System.out.println(st2 == st3);
    System.out.println(st1.hashCode());
    System.out.println(st2.hashCode()); 
    System.out.println(st3.hashCode());
    }
}

输入: deep (master *) LanguagePackageInJava $ javac Lecture3.java
输出: deep (master *) LanguagePackageInJava $ java Test
真的


79855167
79855167
79855167

我已经搜索了很多关于这个问题的信息。请告诉我我在思考过程中哪里错了。

【问题讨论】:

  • String.hashCode() 被覆盖以返回相等字符串的相等哈希码。如果您想查看默认值,请使用 System.hashCode()
  • 在池中与字符串的 hashCode 有什么关系?唯一重要的是它包含的字符及其顺序。
  • 您说您搜索过,但您是否阅读过String API?它准确地说明了 hashCode 是如何计算的。
  • 谢谢你,我得到了答案......在查看了字符串 api 之后
  • @shmosel: ITYM System.identityHashCode(Object)

标签: java string heap-memory hashcode string-pool


【解决方案1】:

hashcode 和 equals 方法有合约,所以如果两个字符串对 equals 为真,那么它们的 hashcode 应该是相同的。

【讨论】:

  • 但是 hashCode 取决于地址,那么字符串池中的一个和字符串池外堆中的另一个怎么可能具有相同的 hashCode
  • 字符串哈希码的生成不依赖于变量的地址位置。根据 java doc String.hashcode() Returns a hash code for this string. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
  • 哈希码从不依赖于地址——那是古老的神话。一个对象的哈希码永远不能改变,但是垃圾收集器会移动对象,这意味着对象的地址几乎是随机变化的
猜你喜欢
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2013-07-31
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多