简体   繁体   中英

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? When I began experimenting with the code, I ended up with XXXX when i removed yx[0]=xy[1]. I think it possibly has something to do with the equal signs but I am confused by how it outputs YYYY rather than XYYX.

This is because arrays are references in Java. So assigning xy to yx makes them the same array. So when you overwrite the first index with "Y" they both then have the values {"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 :

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

Will produce some output like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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