gpt4 book ai didi

java - JAVA中String对象的地址

转载 作者:行者123 更新时间:2023-11-30 03:42:18 25 4
gpt4 key购买 nike

我有一个关于 JAVA 中对象地址的问题。

以下是我的代码。

public class StringCompare {

public static void main(String[] args) {
String s1 = "apple";
String s2 = "apple";
String s3 = new String("apple");

boolean b1 = (s1 == s2);
boolean b2 = (s1 == s3);
boolean b3 = s1.equals(s2);

System.out.println(b1); // true
System.out.println(b2); // false
System.out.println(b3); // true

System.out.println("");

System.out.println("Address of s1 = " + Integer.toHexString(s1.hashCode())); // 58b835a
System.out.println("Address of s2 = " + Integer.toHexString(s2.hashCode())); // 58b835a
System.out.println("Address of s3 = " + Integer.toHexString(s3.hashCode())); // 58b835a
}
}

我认为对象(s1和s2)的地址是相同的。
我认为对象(s3)的地址不等于s1,s2。

但是..结果是对象(s1,s2,s3)的地址相同。

enter image description here

我不知道为什么 s1、s2、s3 地址是相同的..

请给我一些建议。
谢谢。

最佳答案

根据 Object.hashCode() 的文档:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

由于String覆盖了equals(),它也覆盖了hashCode()以履行此契约(Contract)。这意味着 equals() 的两个不同对象仍将具有相同的哈希码。请注意,这意味着哈希码不是对象的地址。 (尽管如此,Object.hashCode() 中的默认实现返回对象本身的唯一标识符,这有点类似于它的地址。请注意,这满足 equals() 契约(Contract),因为默认实现仅在比较对同一对象的两个引用时返回 true。)

关于java - JAVA中String对象的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26570342/

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