如何在 Java 中遍历一个 2D ArrayList 并填充它? [英] How do I loop thorough a 2D ArrayList in Java and fill it?

查看:23
本文介绍了如何在 Java 中遍历一个 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-loop 循环遍历外部 ArrayList,j-loop 循环遍历 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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆