PDA

View Full Version : Clarification on nested arrays




Darran
Nov 3, 2008, 09:10 PM
I am working on a Java question which involves simulating the movement of a billiard ball. I have my logic all panned out, just that it has some holes in it.

Can anyone explain what is a nested array? Is it the same as a 2 dimensional array (e.g. int[][] coordinates;)? Or is it as it says, an array inside an array.

Help would be greatly appreciated.



HiRez
Nov 3, 2008, 10:02 PM
Generally, they would be the same thing. It's an array OF arrays, in other words an array where each element is itself another array.

When people talk about two-dimensional arrays, they usually mean regular arrays, where each inner array has the same number of elements such that it could be visualized as a rectangular grid of cells (this is sometimes also known as a matrix).


****
****
****
****
****

In a ragged array, the inner arrays have variable numbers of elements.


***
********
****
****
*
******

I believe the term "nested array" can refer to either a regular or ragged multidimensional array (array of arrays).

Darran
Nov 3, 2008, 10:49 PM
Thank you for taking the time to explain it.

So can I safely conclude that a nested array could be a regular or ragged array?

In my case, since I need to trace the movement of the ball, I would be making use of a regular array.

lee1210
Nov 3, 2008, 11:00 PM
Java treats multidimensional arrays as a list of arrays, rather than simply setting up enough memory for rows*columns as some languages might. This means that:

int[][] multiArr = new int[5][10];
int[] singleArr = multiArr[0];


Works just fine. multiArr[0] is an array of 10 integers. If you want a jagged array, you have to do something like:
int[][] multiArr = new int[5][];
multiArr[0] = new int[6];
multiArr[1] = new int[4];
multiArr[2] = new int[9];
multiArr[3] = new int[2];
multiArr[4] = new int[5];

In this case, it seems like a rectangular array would do:
class ballState {
int row;
int col;
bool pocketed;
}
public static void main(String args[]) {
int[][] tableRepresentation = new int[25][49];
ballState[] ballStates = new ballState[16]; //Ball 0 is the cue ball
initBallState(ballStates);

}

-Lee