英文:
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
应该在字符串池中,
ab1
和 ab2
在堆中,具有不同的地址,作为不同的对象。
但是所有三者都得到了相同的地址。
英文:
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 && value.length > 0) {
char val[] = value;
for (int i = 0; i < 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论