tags:

views:

54

answers:

3
package javaapplication8;

public class Main {

   public static void main(String[] args) {
     int[] list1 = {1, 2, 3,4};
     int[] list2 = {5, 6, 7,8};

     for (int i = 0; i < list2.length; i++){
       System.out.print(list2[i] + " ");
     }
     System.out.println("");

     list2 = list1;

     for (int i = 0; i < list2.length; i++){
       System.out.print(list2[i] + " ");
     }
     System.out.println("");

     //Change list1
     list1[0] = -1;

     //Change list2
     list2[3] = -4;

     //List1 output
     for (int i = 0; i < list1.length; i++){
       System.out.print(list1[i] + " ");
     }
     System.out.println("");

     //List2 output
     for (int i = 0; i < list2.length; i++){
       System.out.print(list2[i] + " ");
     }
     System.out.println("");

     //Set list1
     list1 = new int[2];
     list1[0] = 100;
     list1[1] = 99;

     //List1 output
     for (int i = 0; i < list1.length; i++){
       System.out.print(list1[i] + " ");
     }
     System.out.println("");

     //List2 output
     for (int i = 0; i < list2.length; i++){
       System.out.print(list2[i] + " ");
     }
     System.out.println("");

   }
}

run:

5 6 7 8 
1 2 3 4 
-1 2 3 -4 
-1 2 3 -4 
100 99
-1 2 3 -4 
+2  A: 

List 1 and List 2 are pointing to same array object after you do List2 = list1;

so doing List2[3] = -4; actually does it for array object that earlier was pointed by List1.

and remember the array object that was earlier related to List2 now stands for garbage collection.

So earlier when u did List1 = x and List2 = y there were two array objects in the memory pointed out by list1 and list2 variables. However after doing list2 = list1 u made both variables point to x array and the other array is free now and java will need to recollect this memory sometime and hence whatever changes ur doing is done to object x rather than y

sushil bharwani
so if you change list2 in any way shape or form way later down the line. you are basically changing list1 since they are referencing the same point? is that right?
CuriousStudent
yes you are right. The only thing that needs to get clarified is there are objects that recide in memory and then there are variables pointing to these objects so next time look for where your variable is pointing to.
sushil bharwani
A: 

Java arrays are stored by reference, thus after calling list2 = list1; both variables reference the same array. Use list2 = Arrays.copyOf(list1, list1.length).

Arian
thank you very much
CuriousStudent
+1  A: 

When you do list2 = list1; in Java, you're not actually copying the array, you're copying a reference to that array.

So you have only one array in memory, and both your list and list2 are pointing to that array. So any modification done to any of the variables also affects the other one.

If you want to create a copy of an array, have a look at the System.arraycopy method.

Vivien Barousse
thank you very much
CuriousStudent