0

I want to copy an array, but I don't know its size. I pasted the class and method below.

public MyClass {

private int map[][];

public void setMap(int[][] map){

 //my code here

    }
}

Of course, this way doesn't work. Because (as I said) I don't know the size.

int map[][] = new int[N][N];
for (int[] i : map)
for (int j : i)
i[j] = 1;
dmcgrandle
  • 5,934
  • 1
  • 19
  • 38

1 Answers1

0

You can find the number of rows in your array and columns by using the .length() function. You can then initialize a 2D array with the same number of rows and columns by doing the following:

//array.length() is the number of rows. 
//array[0].length() takes the first row and gives you the number of columns.
int map[][] = new int[array.length][array[0].length];

Now, to copy the array called array, you can do the following:

for (int i = 0; i < array.length(); i++){
    for(int j = 0; j < array.length(); j++){
        map[i][j] = array[i][j];
    }
}

This is how you will copy your two-dimensional array, array, into your new array, map. Hope this helps!

Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
  • Your line of code does not copy an array at all – azro Nov 10 '18 at 21:16
  • I've no certainty if number of rows and columns are equal. –  Nov 10 '18 at 21:18
  • I have changed it. Now it copies the array, `array`, into the 2D array, `map`. – Ishaan Javali Nov 10 '18 at 21:19
  • Number of columns is different than number of rows. –  Nov 10 '18 at 21:25
  • Then, since each row has the same number of columns, you can say `array[0].length()` to get the number of columns, since `array[0]` will give you an array, the first row. Then, `array[0].length` will give you the number of columns! This should work now! – Ishaan Javali Nov 10 '18 at 21:27
  • Yes! The way to solve it was..primitive. It's little bit too late for programming. Thanks for your help –  Nov 10 '18 at 21:32
  • If this helped you, please consider upvoting it. You're welcome! – Ishaan Javali Nov 10 '18 at 21:33
  • `length` is not a function call, it is a property, so your code should be `array.length`, not `array.length()`. – nickb Nov 10 '18 at 22:03
  • Thanks for the feedback. I wasn't actually testing the code, so I didn't quite realize that. I'll change it in my answer. But shouldn't it be `array.length()` in the for loops? – Ishaan Javali Nov 10 '18 at 22:05