- 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的生命週期也會隨之結束。