Question

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.

Was it helpful?

Solution

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>.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top