简体   繁体   中英

Multi-dimensional arrays: Variable length row?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM