简体   繁体   English

Java:动态调整二维数组中的列的大小

[英]Java: Dynamically size Columns in 2D Array

How can I size my columns dynamically to support a possible ragged array? 如何动态调整列大小以支持可能出现的参差不齐的数组?

int[][] x;
x = new int[3][] //makes 3 rows
col = 1;
for( int i = 0; i < x.length; i++){
  x = new int[i][col]
  col++;  }

Would the above code assign each col length? 上面的代码会分配每个col长度吗?

Thank you in advance for any help. 预先感谢您的任何帮助。

since you are re-assigning x , what you are doing is creating the entire 2D array each loop, which is wrong. 由于您要重新分配x ,因此您正在做的是在每个循环中创建整个2D数组,这是错误的。

You need to do inside your loop: 您需要在循环中执行以下操作:

x[i] = new int[col];
// create the single reference
int[][] x;

// create the array of references 
x = new int[3][] //makes 3 rows

int col = 1;
for( int i = 0; i < x.length; i++){
    // this create the second level of arrays // answer
    x[i] = new int[col];
    col++;  
}

More on 2D Arrays. 有关2D阵列的更多信息。 - https://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm -https://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm

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

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