while中使用List.iterator().hasNext()为什么会出现无限循环
来源:互联网 发布:离线阅读小说软件 编辑:程序博客网 时间:2024/05/29 09:33
初学java的同学往往会犯这样一个错误,就是在在while循环中直接使用List.iterator().hasNext()来遍历一个Litst,就像是下面这段程序一样:
public class IteratorTest {public static void main(String [] args){List<String> testList = new ArrayList<String>() ;testList.add("hello");while(testList.iterator().hasNext()){System.out.println(testList.iterator().next());System.out.println(testList.iterator().equals(testList.iterator()) );}}}
但是往往运行的到的是一个无限循环,很多初学者往往会觉得很奇怪,为什么会出现这种情况呢,我明明已经写了next()了。这是因为testList.iterator()每次都会创建出一个新的Iterator实现对象,这样的话就相当于每次都是一个新的Iterator实现对象去判断hashNext(),得到的肯定是true,所以才产生了无限循环。
因此正确的List遍历方法是要通过一个固定的Iterator实现对象去参加遍历,这样次在进行循环条件判断时候才不会因为Iterator实现对象的不同而产生错误。正确的写法如下:
public class IteratorTest {public static void main(String [] args){List<String> testList = new ArrayList<String>() ;testList.add("hello");Iterator iterator = testList.iterator() ; while(iterator.hasNext()) {System.out.println(iterator.next());System.out.println(iterator.equals(iterator));}}}
0 0
- while中使用List.iterator().hasNext()为什么会出现无限循环
- 为什么JDK源码中,无限循环大多使用for(;;)而不是while(true)?
- 为什么 会出现 输入字母 无限循环的情况呢?
- Iterator中hasNext(), next()
- Iterator中hasNext(), next()
- Iterator中hasNext(), next()
- Iterator中hasNext(), next()
- 【java基础】解决Java中 while(Scanner.hasNext())一直为死循环的问题!
- Iterator中next和hasnext的区别
- mongodb AggregationOutput list.iterator() 无限循环的问题
- While(true)无限循环
- 【iOS开发-104】SQLite使用:注意查询时分步写while会出现死循环
- vfork为什么会出现死循环
- while循环+list+each结合使用 php
- 在Java中使用循环定义会出现哪些问题
- C++中为什么有时候会出现使用cin后在再使用getchar()会没有用
- 输出一串字符中第一个只出现一次的字符/不能使用while/for循环
- C语言中为什么会出现UL?
- centos6.4 安装 mysql5.5 confilt冲突 mysql5.1 lib 解决
- Codeforces Round #274 (Div. 2) B
- SSD7数据库系统实验Exercise2答案
- C++ 60分钟入门教程 - 2、C++与C语言的区别
- 让js具有面向对象的特性
- while中使用List.iterator().hasNext()为什么会出现无限循环
- 《实例妙解 Cocos2d-x 游戏开发》反馈勘误
- 在omnet++上仿真无线传感网络1
- ORCL基础总结
- JSP向后台传值以及hibernate向数据库传值的时候,中文乱码的问题
- 也来谈谈函数返回引用 int& fun(int &x);
- 读《乌合之众---第一章(群体的一般特征)》
- 推荐HTTP方式的OpenAPI的调试、测试工具:HttpRequester
- sass安装