简体   繁体   English

多维数组:可变长度行?

[英]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] 以反转方式使用数组作为array[column][row]而不是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> .) (或者甚至更好,在单独的类中封装您的“行”概念,因此您有一个List<Row> 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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