package 容器2;
import java.util.*;
public class IteratorTraverse {
public static void main(String[] args) {
Collection<Integer>collection = new ArrayList<Integer>();
for(int i=1;i<6;i++){
collection.add(i);
}
System.out.println("集合中的偶数是:");
//使用第一种输出方式
for(Iterator<Integer> it = collection.iterator();it.hasNext();){
if(it.next()%2!=0){
it.remove();
}
}
System.out.println(collection);
//使用第二种方式,Iterator迭代器输出
for(Iterator<Integer> it = collection.iterator();it.hasNext();){
System.out.print(it.next()+" ");
}
System.out.println();
//使用for循环遍历集合
System.out.print("集合中的元素是:[ ");
for(Integer value:collection){
System.out.print(value+" ");
}
System.out.print(" ]");
System.out.println();
//使用普通for循环遍历集合
System.out.print("集合中的元素是:[");
for(int i=1;i<collection.size();i++){
System.out.print(" "+((ArrayList<Integer>) collection).get(i));
}
System.out.println(" ]");
}
}
几种遍历集合的方法
最新推荐文章于 2023-05-24 19:57:36 发布