我如何循环彻底在Java 2D ArrayList和补吗? [英] How do I loop thorough a 2D ArrayList in Java and fill it?
问题描述
我试图用2D的ArrayList Java编写的。
我的定义是:
I am trying to use 2D arrayLists in Java. I have the definition:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
我怎么能环通过它,并从1开始的数字输入?
我知道我可以通过访问特定指数:
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?
感谢
推荐答案
您可以使用嵌套的for循环。 i-循环遍历外ArrayList和第j环通过 myList中
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
}
}
编辑:你再替换填充//做的东西
与
myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list
A注:如果myList中最初未填充,使用循环 .size()
将无法正常工作作为你不能使用获得(SOME_INDEX)
上的的ArrayList
不含指数。您将需要循环从0到要添加值的数量,在第一循环中创建一个新的列表,使用。新增(YOUR_VALUE)
附加新价值在每次迭代到这个新的列表,然后添加新名单 myList中
。请参见肯的回答一个很好的例子。
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.
这篇关于我如何循环彻底在Java 2D ArrayList和补吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!