Java 使用 for-each 循环打印 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9813310/
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-08-16 08:00:35  来源:igfitidea点击:

Print an ArrayList with a for-each loop

javafor-looparraylist

提问by Jordan Westlund

Given the following exists in a class, how do I write a for-each that prints each item in the list?

鉴于类中存在以下内容,我如何编写一个 for-each 来打印列表中的每个项目?

private ArrayList<String> list;
list = new ArrayList<String>();

I have:

我有:

for (String object: list) {
    System.out.println(object);
}

回答by Andreas Dolk

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

您的代码有效。如果您没有任何输出,您可能“忘记”将一些值添加到列表中:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

回答by Pranjal Gupta

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}