Smi28
Smi28

Reputation: 57

replacing a row in a 2D array

I have the following two arrays:

int [][]nums={{1,2,3},{4,5,6},{7,8,9}};
int []sums= {44,45,46};

I want to replace 7 8 9 of nums with 44 45 46 of sums. This is what I am currently doing:

for(int i=0; i<sums.length; i++){
  for(int j=0 ; j< nums[2].length; j++){
    nums[2][j]=sums[i];
  } 
}

However, this makes nums[2]={46,46,46} Can someone guide me as to what I am doing wrong?

Upvotes: 1

Views: 3866

Answers (1)

Anderson Vieira
Anderson Vieira

Reputation: 9049

You don't need nested loops in this case. You could do:

for (int i = 0; i < sums.length; i++) {
    nums[2][i] = sums[i];
}

Or you could assign it directly with no loop:

int[][] nums = {{1,2,3}, {4,5,6}, {7,8,9}};
int[] sums = {44,45,46};
nums[2] = sums;
System.out.println(Arrays.deepToString(nums));

Output:

[[1, 2, 3], [4, 5, 6], [44, 45, 46]]

The difference is that the first solution will copy the elements from sums to nums[2], while the second solution will make nums[2] reference the same object as sums. So if you choose the second option and change sums later, nums[2] will also change.

Upvotes: 2

Related Questions