2个String对象具有相同的地址

huangapple go评论68阅读模式
英文:

2 String object have same address

问题

这是根据Java8版本。

    String s = "Hello1";
    String ab1 = new String(s);
    String ab2 = new String(s);
    System.out.println("s = " + s.hashCode());
    System.out.println("ab1 = " + ab1.hashCode());
    System.out.println("ab2 = " + ab2.hashCode());

输出结果如下:

s = -2137068097
ab1 = -2137068097
ab2 = -2137068097

变量 s 应该在字符串池中,
ab1ab2 在堆中,具有不同的地址,作为不同的对象。

但是所有三者都得到了相同的地址。

英文:

This is as per Java8

    String s = "Hello1";
    String ab1 = new String(s) ;
    String ab2 = new String(s) ;
    System.out.println("s = " + s.hashCode());
    System.out.println("ab1 = " + ab1.hashCode());
    System.out.println("ab2 = " + ab2.hashCode());

output is coming as

s = -2137068097
ab1 = -2137068097
ab2 = -2137068097

s should be on String pool
ab1 and ab2 is on heap with different address as different object

but all 3 got same address

答案1

得分: 2

HashCode不是堆地址或内存位置。查看String hashCode的实现

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

因此对于长度相同且经过ASCII转换后相加返回相同值的值将得到相同的哈希码
英文:

HashCode is not Heap Address/memory Location. <br>
Have a look at String hashCode implementation

public int hashCode() {
    int h = hash;
    if (h == 0 &amp;&amp; value.length &gt; 0) {
        char val[] = value;

        for (int i = 0; i &lt; value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

Hence for same length value & value whose ascii conversion and then addition returns same value gives same hashcode.

答案2

得分: 0

以下是翻译好的内容:

哈希码并非实际的内存地址值。为了证明这一点,我们可以在所有三种变量组合上使用 == 运算符。所有三种情况都返回 false,以确认它们的内存地址不同。

System.out.println(s == ab1);
System.out.println(ab1 == ab2);
System.out.println(s == ab2);
英文:

The hashcode is not the actual memory address value. To prove this, we can use the == operator on the all three combination of variables. All three gives false as to confirm that the memory address are not the same for them.

System.out.println(s == ab1);
System.out.println(ab1 == ab2);
System.out.println(s == ab2);

huangapple
  • 本文由 发表于 2020年10月10日 05:45:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64287708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定