我不明白在这个问题中等号如何影响字符串数组 (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]);
}
}
当我 运行 通过 Eclipse 和其他程序时它总是打印 YYYY 而不是 XYYX 这是怎么回事?当我开始试验代码时,当我删除 yx[0]=xy[1] 时,我得到了 XXXX。我认为它可能与等号有关,但我对它如何输出 YYYY 而不是 XYYX 感到困惑。
这是因为数组是 Java 中的引用。因此将 xy
分配给 yx
使它们成为相同的数组。因此,当您用 "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]);
}
}
如果您打印出两个数组,您可以看到这一点。在 yx = xy
之后添加:
System.out.println(xy);
System.out.println(yx);
会产生这样的输出:
[Ljava.lang.String;@3caeaf62
[Ljava.lang.String;@3caeaf62
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]);
}
}
当我 运行 通过 Eclipse 和其他程序时它总是打印 YYYY 而不是 XYYX 这是怎么回事?当我开始试验代码时,当我删除 yx[0]=xy[1] 时,我得到了 XXXX。我认为它可能与等号有关,但我对它如何输出 YYYY 而不是 XYYX 感到困惑。
这是因为数组是 Java 中的引用。因此将 xy
分配给 yx
使它们成为相同的数组。因此,当您用 "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]);
}
}
如果您打印出两个数组,您可以看到这一点。在 yx = xy
之后添加:
System.out.println(xy);
System.out.println(yx);
会产生这样的输出:
[Ljava.lang.String;@3caeaf62
[Ljava.lang.String;@3caeaf62