简体   繁体   English

我不明白在这个问题中字符串数组是如何受等号影响的(Java)

[英]I do not understand how String arrays are effected by equal signs in this problem (Java)

 import java.util.ArrayList; public class MyClass { public static void main(String args[]) { String[] xy = {"X", "Y"}; String[] yx = xy; yx[0]=xy[1]; yx[1]=xy[0]; System.out.println(xy[0] + xy[1]+yx[0]+yx[1]); } }

When I run this through Eclipse and other programs it always prints YYYY instead of XYYX how is this?当我通过 Eclipse 和其他程序运行它时,它总是打印 YYYY 而不是 XYYX,这是怎么回事? When I began experimenting with the code, I ended up with XXXX when i removed yx[0]=xy[1].当我开始尝试代码时,当我删除 yx[0]=xy[1] 时,我最终得到了 XXXX。 I think it possibly has something to do with the equal signs but I am confused by how it outputs YYYY rather than XYYX.我认为它可能与等号有关,但我对它如何输出 YYYY 而不是 XYYX 感到困惑。

This is because arrays are references in Java.这是因为数组是 Java 中的引用。 So assigning xy to yx makes them the same array.因此将xy分配给yx使它们成为相同的数组。 So when you overwrite the first index with "Y" they both then have the values {"Y", "Y"} .因此,当您用"Y"覆盖第一个索引时,它们的值都为{"Y", "Y"}

import java.util.ArrayList;
public class MyClass {
    public static void main(String args[]) {
     // xy[0] = "X" and xy[1] = "Y"
     String[] xy = {"X", "Y"};
     // arrays are references, so yx and xy are now the same array
     String[] yx = xy;
     // yx[0] = "Y"
     yx[0]=xy[1];
     // yx[1] = "Y", this is because they refer to the same array
     yx[1]=xy[0];
     System.out.println(xy[0] + xy[1]+yx[0]+yx[1]);
    }
}

If you print out both arrays you can see this.如果您打印出两个数组,您可以看到这一点。 Adding this after yx = xy :yx = xy之后添加:

System.out.println(xy);
System.out.println(yx);

Will produce some output like this:会产生一些这样的输出:

[Ljava.lang.String;@3caeaf62
[Ljava.lang.String;@3caeaf62

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM