Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java字符串对象的相等和引用_Java_String_Oop_Object - Fatal编程技术网

Java字符串对象的相等和引用

Java字符串对象的相等和引用,java,string,oop,object,Java,String,Oop,Object,我有以下代码: 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.hashCo

我有以下代码:

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
     }
}
首先,我创建两个字符串x和y。然后我检查它们的哈希代码,它们是相同的,这意味着它们是一个对象,它们指向一个内存位置。但是当我改变y值时,x的值不会改变。如果我再次检查它们的哈希代码,它们是不同的,这意味着两个不同的对象和两个不同的内存位置。为什么会这样?为什么y改变时x不改变?(因为我们只是在更改一个内存的内容)

如问题所示,我使用了hashcode

更新: 我的困惑有两个原因:

a) 我认为相同的hashcode意味着相同的对象(你可以看一看并提出问题来详细解释我的错误)


b) 字符串是不可变的,如果值更改,将创建新字符串(如下面的答案所述)。

Java中的字符串是不可变的。您不是在“更改y的值”,而是在创建一个新字符串并将其分配给y。由于您没有为x分配任何其他内容,因此它仍然会引用您之前在那里使用的字符串。

我认为这个问题最终源于您的误解,即
x
y
是对象
x
y
不是对象。

x
y
是变量,由于
String
是引用类型,
x
y
存储对对象的引用。
=
赋值运算符更改这些变量存储的引用

在这两行中:

String x = "a";
String y = "a";
x
y
存储引用同一对象的引用

但是当您执行
y=y+“b”
时,
y+“b”
将创建一个新对象。然后
=
使
y
存储对该新对象的引用,因此
y
不再指向与
x
相同的对象。看,具有相同的哈希码并不意味着对象是相同的!Hashcode是一个int,所以这里只有40亿个可能的hashcodes,但是还有更多可能的字符串,所以一定存在冲突。