# expanding a multidimensional array?

MR Chen
Ranch Hand
Posts: 32
OK, so I'm writing a game, and it has a board. 8x8 squares. Like a checkerboard. I'm representing it with a multidimensional array.

Now, let's suppose that, during the game, I want to expand the board to a 10x10 size (i.e. add one additional square around the border of the old board).

Can I do this with arraycopy()?

The few references that I've seen to arraycopy() have only used single-dimension arrays, so I'm wondering how the syntax would work for a multidimensional array.

Thanks,
Mike

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
A "2D array" in Java is actually a 1D array of 1D arrays; i.e., your 8x8 board is one object that's a 1D array of 8 arrays, and 8 more objects that are 1D arrays of squares.

System.arraycopy() can help you individually copy each of these nine objects, but it can't do it all at once. You're going to have to do something like:

It would be possible to write this with less code; I did it this way to make it very obvious what's going on.

greg buela
Ranch Hand
Posts: 71
I would use arraycopy() looping through rows, that is, copying row by row.

This code will copy all rows from board (0 - 7) into rows (1 - 8) of newboard. For each row, it copies 8 positions from board starting at 0, to newboard starting at 1.
You would have to initialize the new cells accordingly...

Edit: I screwed up a little bit on the array declarations, nevermind, look at Ernest's code I rarely use jagged arrays!
Edit II: Just to point out that this code copies the original board centered on the new one, yielding new cells all around. Ernest's version adds rows and columns at the end.

[ October 05, 2007: Message edited by: greg buela ]
[ October 05, 2007: Message edited by: greg buela ]

MR Chen
Ranch Hand
Posts: 32
Ernest/greg: