Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Darran

macrumors member
Original poster
Mar 31, 2008
77
0
Singapore
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

macrumors 603
Jan 6, 2004
6,265
2,630
Western US
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).

Code:
****
****
****
****
****

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

Code:
***
********
****
****
*
******

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

Darran

macrumors member
Original poster
Mar 31, 2008
77
0
Singapore
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

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
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:

Code:
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:
Code:
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:
Code:
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.