几种遍历集合的方法

来源:互联网 发布:js数组each遍历 编辑:程序博客网 时间:2024/06/03 16:20
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(" ]");}}