简体   繁体   中英

Why does this program print out “4 2 1 0”?

Can someone explain the output of this code? I'm very confused. Before I compiled this code, I thought the output was "4 1 2 3". After compiling the code, it is "4 2 1 0". I'm not sure why so i'm wondering if someone can explain it to me?

public class activity1
{
public static void main(String[]args)
{
//Declare and initialize array
int []list1 = {3,2,1,4};            
int [] list2 = {1,2,3};
list2= list1;
list1[0]=0;
list1[1]=1;
list2[2]=2;
//Create for loop   
for (int i = list2.length-1; i>=0;i--)
{
System.out.print(list2[i] + " ");//print out the array
}
}
}

After list2= list1; there is only one array. {3, 2, 1, 4}

Then, it's modified to {0, 1, 2, 4} and then it's printed backwards.

You can debug and see for yourself what the code is doing at every line:

public static void main(String[] args) {
    // Declare and initialize array
    int[] list1 = {3, 2, 1, 4};
    int[] list2 = {1, 2, 3};
    list2 = list1; // list1 = [3, 2, 1, 4] list2 = [3, 2, 1, 4]
    list1[0] = 0; // list1 = [0, 2, 1, 4] list2 = [0, 2, 1, 4]
    list1[1] = 1; // list1 = [0, 1, 1, 4] list2 = [0, 1, 1, 4]
    list2[2] = 2; // list1 = [0, 1, 2, 4] list2 = [0, 1, 2, 4]

    // Create for loop
    // You are printing list2 in reverse order
    for (int i = list2.length - 1; i >= 0; i--) {
      System.out.print(list2[i] + " ");// print out the array
    }
}

The assignment is just moving a reference to list1 into the list2 variable. So, both variables reference the same array. If you want to copy the array, you will need copy each item from list1 to list 2.

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