星空网 > 软件开发 > Java

使用iterator出现的死循环

 1 public static void main(String[] args) 2   { 3     List<String> list = new ArrayList<String>(); 4      5     list.add("yaoyuan"); 6     list.add("tiancai"); 7      8     Iterator it = list.iterator(); 9     String s = "";10     while(it.hasNext()){11       System.out.println("aaa");12       if(s == null){13         System.out.println("@@@");14         continue;15       }16 //      System.out.println(it.next());17       if(((String)it.next()).equals("yaoyuan")){18         it.remove();19         20       }21     }22     for (String string : list)23     {24       System.out.println(string);25     }26   }

在以上代码中,若临时变量s为空的话,则会进入死循环。

这是由于没有正确的理解continue的用法,continue会结束其后跟随的语句而直接开始下一次的循环,在这里s为空,则直接进行下一次循环,没有执行到it.next(),所有iterator的序列值没有发生变化,hasNext永远都是真,进入死循环。

 

另外,在对集合做遍历操作的时候不允许有插入或者删除操作,否则会抛异常。若要删除可以使用iterator的remove方法,也可以在元素中做一个标记,循环结束后再做操作。




原标题:使用iterator出现的死循环

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

国内海运到印尼:https://www.goluckyvip.com/tag/99236.html
海运 到印尼:https://www.goluckyvip.com/tag/99237.html
到印尼 海运:https://www.goluckyvip.com/tag/99238.html
广州到尼日利亚海运:https://www.goluckyvip.com/tag/99239.html
海运中国到南美:https://www.goluckyvip.com/tag/99240.html
中国到南美海运:https://www.goluckyvip.com/tag/99241.html
一夜之间大批卖家货物被偷,又迎大量Listing将被下架!跨境赚钱"好日子"到头了?:https://www.goluckyvip.com/news/220219.html
晚上沈阳市区哪里好玩的地方 晚上沈阳有什么好玩的地方:https://www.vstour.cn/a/410235.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流