迭代数组列表并打印数组中的每个元素

时间:2015-11-06 09:10:21

标签: java arrays arraylist iterator

我似乎在解决问题的逻辑方面遇到了麻烦。我想要做的是有一个数组列表。每个数组包含2个字符串。

我正在尝试遍历我的List,然后打印数组的元素。我似乎卡在打印第一个数组(这是我的代码所做的),虽然我陷入逻辑。

    public static void main(String[] args) {
    List<List<String>> addresses = new ArrayList<List<String>>();

    ArrayList<String> singleAddress1 = new ArrayList<String>();
    singleAddress1.add("17 Fake Street");
    singleAddress1.add("18 Fake Street");
    ArrayList<String> singleAddress2 = new ArrayList<String>();
    singleAddress2.add("Phoney town");
    singleAddress2.add("not real town");
    ArrayList<String> singleAddress3 = new ArrayList<String>();
    singleAddress3.add("sillyname town");
    singleAddress3.add("alsosilly town");
    addresses.add(singleAddress1);
    addresses.add(singleAddress2);
    addresses.add(singleAddress3);

    System.out.print("Original contents of al: " + addresses + "\n");
    Iterator itr = addresses.iterator();
    while (itr.hasNext()) {
        Object element = itr.next();
        System.out.print(element + "\n");
        for (int i = 0; i < singleAddress1.size(); i++) {
            System.out.println(singleAddress1.get(i));
        }
        itr.remove();
    }
}
}

2 个答案:

答案 0 :(得分:2)

当您在外部数组列表addresses上进行迭代时,在内部最终会迭代相同的singleAddress1,而不是使用for (int i = 0; i < singleAddress1.size(); i++) {从迭代器获取的所有列表元素。

你的迭代循环应该是:

Iterator<List<String>> itr = addresses.iterator();
while (itr.hasNext()) {
    List<String> element = itr.next();
    ^^^^^^^^^^^^
    System.out.print(element + "\n");
    for (int i = 0; i < element.size(); i++) {
                        ^^^^^^^^
        System.out.println(element.get(i));
    }
    itr.remove();
}

答案 1 :(得分:1)

为什么不使用简单的for-each循环:

for(List<String> list:addresses)
{
    for(String str:list)
    {
        System.out.println(str);
    }
}