用foreach遍历集合和数组

来源:互联网 发布:软件架构设计 编辑:程序博客网 时间:2024/06/05 08:06
public class Test{
public static void main(String[] args) {
List<String> list = new ArrayList();
list.add("南京");
list.add("北京");
list.add("上海");
System.out.println("用foreach遍历集合:");
for(String string:list){
System.out.println(string);
}

String[] strs = new String[list.size()];
list.toArray(strs);
System.out.println("\n用foreach遍历数组");
for(String string:strs){
System.out.println(string);
}
}

}


foreach是for循环遍历集合和数组的一种简写形式。

对于集合类数据的遍历,应使用foreach。

0 0