我有以下代码:
public class Test{
public static void main(String []args){
String x = "a";
String y = "a";
System.out.println(System.identityHashCode(x) == System.identityHashCode(y)); //true
System.out.println(x.hashCode() == y.hashCode()); //true
y = y+"b";
System.out.println(x); // "a"
System.out.println(y); // "ab"
System.out.println(System.identityHashCode(x) == System.identityHashCode(y)); //false
System.out.println(x.hashCode() == y.hashCode()); //false
}
}
首先我创建 2 个字符串 x 和 y。然后我检查它们的哈希码,它们是相同的,这意味着它们是一个对象,并且它们指向一个内存位置。但是当我改变 y 值时,x 的值不会改变。如果我再次检查它们的哈希码,它们是不同的,这意味着 2 个不同的对象和 2 个不同的内存位置。为什么会发生这种情况?为什么当 y 改变时 x 不改变? (因为我们只是改变一个内存的内容)
我使用哈希码为 this问题表明。
更新: 我的困惑有两个原因:
a) 我认为相同的哈希码意味着相同的对象(您可以查看 this 和 this 问题,详细解释为什么我错了。)
b) 字符串是不可变的,如果值发生变化,则会创建新字符串(如下面的答案中所述。)
最佳答案
Java 中的字符串是不可变的。您不是“更改 y 的值”,而是创建一个新字符串并将其分配给 y。由于您没有为 x 分配任何其他内容,因此它仍然会引用您之前的字符串。
关于Java String 对象的相等性和引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61012358/