Reza
Reza

Reputation: 151

incorrect variable change in java

I have a problem in Eclipse. Why is the value of oldList different in LogCat while I don't change it between the tow Log command?

First I have an initialize method:

private void initialize() {

    list[0][0] = 2;
    list[0][1] = 4;
    list[1][0] = 3;
    list[1][1] = 7;

    oldList = list;

    going();
}

and in the going method, I printed oldList twice :

private void going() {

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            Log.i("Log", "oldList = " + oldList[i][j]);
        }
    }
    Log.i("Log", "---------------------------");

    //    ----------------------------------------------------
    list[0][0] = 0;
    list[0][1] = 5;

    list[1][0] = 0;
    list[1][1] = 0;
    //    ----------------------------------------------------

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            Log.i("Log", "oldList = " + oldList[i][j]);
        }
    }
}

but the two results is different in LogCat :

oldList = 2
oldList = 4
oldList = 3
oldList = 7
---------------------------
oldList = 0
oldList = 5
oldList = 0
oldList = 0

While i don't change it between the two logs. I just change the value of list, not oldList. Why does the output change?

Upvotes: 6

Views: 271

Answers (3)

kayosoufiane
kayosoufiane

Reputation: 81

you can try this :

private void initialize() {
   list[0][0] = 2;
   list[0][1] = 4;
   list[1][0] = 3;
   list[1][1] = 7;

   // simply
   oldList[0] = list[0].clone();
   oldList[1] = list[1].clone();

   // or in a greater 2D arrays
   for (int i = 0; i < list.length; i++) {
      System.arraycopy(list[i], 0, oldList[i], 0, list[0].length);
   }

   going();
}

Upvotes: 1

Holger Just
Holger Just

Reputation: 55718

Both list and oldlist refer to the exact same object. When you run

oldlist = list

you have two different "names" referring to the exact same object in memory. When you assign an object (in your case the array) to a variable, this object will not be copied.

Thus, as you change the list array in your going method, you are changing the object referred to by both list and oldlist.

Upvotes: 4

Andres
Andres

Reputation: 10707

oldlist and list are two references that point to the same array.

Upvotes: 3

Related Questions