5

It is possible to do variable length columns such as:

private int k[][] = new int[3][];

for(int i = 0; i < k.length; i++) {
   k[i] = new int[i+1];
}

I was wondering if it was possible to do variable length rows, if you know the length of a column?:

private int k[][] = new int[][5];

for(int i = 0; i < k.length; i++) {
   // How would you do this?
}

Thank you.

Volatile
  • 677
  • 2
  • 8
  • 17
  • 3
    Arrays in Java are always of a fixed length. If you need something variable in size, use ArrayList. It can also be nested, if you really have to do that. – Till Helge May 22 '13 at 11:23
  • Compiler: Cannot specify an array dimension after an empty dimension – johnchen902 May 22 '13 at 11:24

1 Answers1

4

You can't, basically. A "multi-dimensional" array is just an array of arrays. So you have to know the size of the "outer" array to start with, in order to create it.

So your options are:

  • Use the array in an inverted way as array[column][row] instead of array[row][column]
  • Use a list instead, so you can add new rows as you go:

    List<Object[]> rows = new ArrayList<Object[]>();
    for (SomeData data : someSource) {
        Object[] row = new Object[5];
        ...
        rows.add(row);
    }
    

    (Or even better, encapsulate your concept of a "row" in a separate class, so you have a List<Row>.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194