集合遍历的四种方法
代码如下:
import java.util.*;
public class Demo5 {
public static void main(String[] args) {
List<String> al=new ArrayList<String>();
al.add("1");
al.add("3");
al.add("5");
al.add("7");
al.add("9");
//遍历 第一种for
System.out.print("第一种遍历方式! ");
for(int i=0;i<al.size();i++)
{
String str=al.get(i);
System.out.print(str+" ");
}
System.out.println();
//遍历 二种for each
System.out.print("第二种遍历方式! ");
for(String x:al)
{
System.out.print(x+" ");
}
System.out.println();
//遍历 第三种遍历方式 迭代器(while)
System.out.print("第三种遍历方式! ");
Iterator it=al.iterator();
while(it.hasNext())
{
String str=it.next().toString();
System.out.print(str+" ");
}
System.out.println();
//遍历 第四种遍历方式 迭代器(for)
System.out.print("第四种遍历方式! ");
for(Iterator it1=al.iterator();it1.hasNext();)
{
String str=it1.next().toString();
System.out.print(str+" ");
}
}
}
运行结果:
第一种遍历方式! 1 3 5 7 9
第二种遍历方式! 1 3 5 7 9
第三种遍历方式! 1 3 5 7 9
第四种遍历方式! 1 3 5 7 9