Clarification on nested arrays

Discussion in 'Mac Programming' started by Darran, Nov 3, 2008.

  1. Darran macrumors member

    Joined:
    Mar 31, 2008
    Location:
    Singapore
    #1
    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.
     
  2. HiRez macrumors 603

    HiRez

    Joined:
    Jan 6, 2004
    Location:
    Western US
    #2
    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).
     
  3. Darran thread starter macrumors member

    Joined:
    Mar 31, 2008
    Location:
    Singapore
    #3
    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.
     
  4. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    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
     

Share This Page