[英]Java: Dynamically size Columns in 2D 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++; }
上面的代码会分配每个col长度吗?
预先感谢您的任何帮助。
由于您要重新分配x
,因此您正在做的是在每个循环中创建整个2D数组,这是错误的。
您需要在循环中执行以下操作:
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++;
}
有关2D阵列的更多信息。 -https://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.