Skip to content
Advertisement

Why does changing one entry in a 2D array change the entire column?

//main method
int one = 1;
int[] ones = {one, one, one};
int[][] lotsofones = {ones, ones, ones};
lotsofones[0][1] = 2;
for (int[] array : lotsofones) {
  for (int num : array) {
    System.out.print(num + " ");
  }  
  System.out.println();
}
/*
Expected output:
1 2 1 
1 1 1
1 1 1 

Actual output:
1 2 1
1 2 1 
1 2 1 
*/

Why is this happening? I don’t understand. Why is it changing the entire column instead of just the single entry?

How do I achieve changing only one entry without initializing the 2D array differently? Is it possible?

Advertisement

Answer

Why is it changing the entire column instead of just the single entry?

Because each column, of each row, is the element stored in one same array object on the heap, and changing element in the array referenced with ones, will reflect that change in every other variable, which refers (or will refer) to the same array instance.

int one = 1;
int[] ones = {one, one, one}; //creates 1D array `{1, 1, 1}`
int[][] lotsofones = {ones, ones, ones}; //reuses and puts the same "ones" array, object in three indices of "lotsofones" 2D array

Therefore, changing:

lotsofones[0][1] = 2;

changes entry in ONE array object, that is referenced three times.


How do I achieve changing only one entry without initializing the 2D array differently? Is it possible?

Sure, it is. Just create 2D array by not using the same array object for every element of that 2D array. One way would look like this:

int one = 1;
int size = 3;
int[][] lotsofones = new int[size][size];
for (int i = 0; i < size; i++) {
    for (int j = 0; j < lotsofones[i].length; j++) {
        lotsofones[i][j] = one;
    }
}

lotsofones[0][1] = 2; //this will now change one particular element on one 2D array, instead of changing element in an array that is re-used over and over.

Then,

for (int[] array : lotsofones) {
    for (int num : array) {
        System.out.print(num + " ");
    }
    System.out.println();
}

will output:

1 2 1 
1 1 1 
1 1 1 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement