如何在 Java 中遍历一个 2D ArrayList 并填充它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33509520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:46:53  来源:igfitidea点击:

How do I loop thorough a 2D ArrayList in Java and fill it?

javaarraysarraylist

提问by user2955610

I am trying to use 2D arrayLists in Java. I have the definition:

我正在尝试在 Java 中使用 2D arrayLists。我有定义:

ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();

How can I loop through it and enter in numbers starting from 1? I know that I can access a specific index by using:

如何遍历它并输入从 1 开始的数字?我知道我可以使用以下方法访问特定索引:

myList.get(i).get(j)

Which will get the value. But how do I add to the Matrix?

哪个将获得价值。但是我如何添加到矩阵中?

Thanks

谢谢

回答by bpgeck

You can use a nested for loop. The i-loop loops through the outer ArrayList and the j-loop loops through each individual ArrayList contained by myList

您可以使用嵌套的 for 循环。i-loop 循环遍历外部 ArrayList,j-loop 循环遍历每个单独的 ArrayListmyList

for (int i = 0; i < myList.size(); i++)
{
    for (int j = 0; j < myList.get(i).size(); j++)
    {
        // do stuff
    } 
}

Edit:you then fill it by replacing // do stuffwith

编辑:然后你用替换// do stuff来填充它

myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list

A Note:If the myList is initially unfilled, looping using .size()will not workas you cannot use .get(SOME_INDEX)on an ArrayListcontaining no indices. You will need to loop from 0 to the number of values you wish to add, create a new list within the first loop, use .add(YOUR_VALUE)to append a new value on each iteration to this new list and then add this new list to myList. See Ken's answerfor a perfect example.

注意:如果 myList 最初未填充,则循环 using.size()将不起作用,因为您不能.get(SOME_INDEX)在不ArrayList包含索引的情况下使用。您需要从 0 循环到要添加的值的数量,在第一个循环中创建一个新列表,用于.add(YOUR_VALUE)在每次迭代时将新值附加到此新列表,然后将此新列表添加到myList. 有关完美示例,请参阅Ken 的回答

回答by rajuGT

Use for-eachloop, if you are using Java prior 1.5 version.

如果您使用 Java 1.5 之前的版本,请使用for-each循环。

for(ArrayList<Integer> row : myList) {

  for(Integer intValue : row) {

     // access "row" for inside arraylist or "intValue" for integer value.

  }

}

回答by Ken Geis

Assuming the matrix is not initialized,

假设矩阵未初始化,

int m = 10, n = 10;
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();

for (int i = 0; i < m; i++) {
    List<Integer> row = new ArrayList<Integer>();
    for (int j = 0; j < n; j++) {
        row.add(j);
    }
    matrix.add(row);
}