我是靠谱客的博主 激动棉花糖,这篇文章主要介绍迭代器(Iterator)遍历的两种方法(for和while),现在分享给大家,希望可以做个参考。

  • while循环遍历
复制代码
1
2
3
4
5
6
7
8
9
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循环遍历
复制代码
1
2
3
4
5
6
7
8
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的生命周期也会随之结束。

最后

以上就是激动棉花糖最近收集整理的关于迭代器(Iterator)遍历的两种方法(for和while)的全部内容,更多相关迭代器(Iterator)遍历内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部