Search code examples
javaarraysmultidimensional-arrayinitializationragged

How to create a ragged array in Java


I wanna create a ragged array (two-dimensional array) that the user inserts the values one at a time. I would usually create them like so:
int[][] array = {{1,2,3}, {6,7}} but I don't know their size beforehand.
How can I create an array like that?


Solution

  • You should initialize a jagged/ragged (same thing) array like this: int array[][] = new int[4][]; Then you can (for example):

        array[0] = new int[5];
        array[1] = new int[5];
        array[2] = new int[5];
        array[3] = new int[5];
    

    Then you can:

    for (int i = 0; i < 4; i++){
          for (int j = 0; j < i + 1; j++) {
            array[i][j] = i + j;
          }
    }
    

    And if you want to print:

    for (int i = 0; i < 4; i++) {
          for (int j = 0; j < i + 1; j++)
            System.out.print(array[i][j] + " ");
          System.out.println();
    }
    

    You'll get the output:

    0
    1 2
    2 3 4
    3 4 5 6

    Of course that if you want to get the input from the user you can substitute any assignment here with Scanner.nextInt();.

    Edit after comment: You must specify the size, if you don't wish to do that, then use:

    ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>();