使用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为空的话,则会进入死循环。spa

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

 

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

相关文章
相关标签/搜索