您的位置:首页 > 编程语言 > Java开发

迭代器(Iterator)遍历 a9e5 的两种方法(for和while)

2018-04-01 20:47 316 查看
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的生命周期也会随之结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java基础知识