- while循环遍历
Collection coll = new ArrayList();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
coll.add("abc4");
Iterator it = coll.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
- for循环遍历
Collection coll = new ArrayList();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
coll.add("abc4");
for(Iterator it = coll.iterator(); it.hasNext(); ){
System.out.println(it.next());
}
- 注意:开发中建议使用for循环实现迭代,因为while循环中,it是在while循环体外创建的,因此while循环结束后,it仍然在内存中占据着一定的空间。而使用for循环,在循环结束后,it的生命周期也会随之结束。