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

纵然是瞬间 提交于 2019-12-19 11:56:27

问题


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

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:

myList.get(i).get(j)

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

Thanks


回答1:


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 (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 stuff with

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 work as you cannot use .get(SOME_INDEX) on an ArrayList containing 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 answer for a perfect example.




回答2:


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

for(ArrayList<Integer> row : myList) {

  for(Integer intValue : row) {

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

  }

}



回答3:


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);
}


来源:https://stackoverflow.com/questions/33509520/how-do-i-loop-thorough-a-2d-arraylist-in-java-and-fill-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!