[英]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.