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());
}
}
}