package com.btp.t4; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import org.junit.Test; public class TestIterator { //正确的写法:使用迭代器实集合的遍历 @Test public void Test1(){ Collection coll=new ArrayList(); coll=Arrays.asList(123,"AA",new Date(),"BB"); System.out.println(coll); Iterator i=coll.iterator(); while(i.hasNext()){ System.out.println(i.next()); } } //正确的写法:使用增强foreach循环实现集合的遍历 @Test public void Test3(){ Collection coll=new ArrayList(); coll=Arrays.asList(123,"AA",new Date(),"BB"); System.out.println(coll); for(Object obj:coll)//obj是一个新定义的局部变量,修改obj不会修改coll的值 { System.out.println(obj); } } //错误的写法 @Test public void Test2(){ Collection coll=new ArrayList(); coll=Arrays.asList(123,"AA",new Date(),"BB"); System.out.println(coll); Iterator i=coll.iterator(); while(i.next()!=null){ System.out.println(i.next()); } } }