2017-04-19 62 views
0

有人可以解释这段代码的输出吗?我很困惑。在编译此代码之前,我认为输出是“4 1 2 3”。编译代码后,它是“4 2 1 0”。我不确定为什么所以我想知道是否有人可以向我解释它?这个程序为什么打印出“4 2 1 0”?

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 
} 
} 
} 

回答

2

list2= list1;之后只有一个数组。 {3, 2, 1, 4}

然后,它被修改为{0, 1, 2, 4},然后向后打印。

+0

谢谢!这更有意义! – Jack

0

该分配只是将对list1的引用移动到list2变量中。所以,这两个变量都引用相同的数组。如果你想在阵列复制,则需要每一个项目从列表1复制到列表2.

1

可以调试,看看自己是什么代码是在每行做:

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 
    } 
}