簡體   English   中英

如何用一維填充二維 arrayList?

[英]How can I fill two-dimensional arrayList with one dimensional?

我有一個問題,每當我嘗試用一維填充二維 arrayList (5x5) 時,都會出現索引越界異常。 我猜那是因為方形數組還沒有索引 0 值,但我不知道如何修復它。

ArrayList<Character> c = new ArrayList<>();
        
// Copy character by character into arraylist 
for (int i = 0; i < finalArray.length(); i++) { 
    c.add(i, finalArray.charAt(i));
} 

ArrayList<ArrayList<Character>> square = new ArrayList<>();
//square.add(new ArrayList<>()); 

int k = 0;
for(int i = 0; i < 4; i++){
    for(int j = 0; j < 4; j++){
        square.get(j).add(i, c.get(k));
        k++;
    }
}

在內部循環之前將“行”列表添加到外部列表。 您還為square使用了錯誤的索引。

int k = 0;
for(int i = 0; i < 4; i++){
    square.add(new ArrayList<>()); // Initialize the row
    for(int j = 0; j < 4; j++){
        square.get(i).add(c.get(k++)); // get(i) not get(j)!
    }
}

還要注意其他簡化。

這樣做會更清楚:

int k = 0;
for(int i = 0; i < 4; i++){
    List<Character> row = new ArrayList<>();
    square.add(row);
    for(int j = 0; j < 4; j++){
        row.add(c.get(k++));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM