迭代器(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的生命周期也会随之结束。

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