public class IteratorTest {
@Test
public void test1(){
Collection coll =new ArrayList();
coll.add(123); //自动装箱
coll.add(false);
coll.add(new Date());
coll.add(new String("Tom"));
coll.add(new Person("fengxin",20));
Iterator iterator = coll.iterator();
//方式一:不建议使用
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// System.out.println(iterator.next());
// //异常java.util.NoSuchElementException
// //System.out.println(iterator.next());
//方式二:也不推荐使用
// for (int i = 0; i <coll.size() ; i++) {
// System.out.println(iterator.next());
// }
//方式三:推荐
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
/**
* 迭代器remove()方法
* 在调用next()前不能用remove()。
* 调用一次remove()在下一次next()前也不能掉remove()。
*/
@Test
public void test2(){
Collection coll =new ArrayList();
coll.add(123); //自动装箱
coll.add(false);
coll.add(new Date());
coll.add(new String("Tom"));
coll.add(new Person("fengxin",20));
Iterator iterator = coll.iterator();
while (iterator.hasNext()){
Object obj=iterator.next();
if("Tom".equals(obj)){
iterator.remove();
}
}
iterator = coll.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}