迭代器(Iterator)遍歷的兩種方法(for和while)

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章