Understanding Java Iterator

后端 未结 3 1720
我寻月下人不归
我寻月下人不归 2021-01-20 18:50

If I run the following code, it will print out 3 times duplicate, but when I remove the if statement inside the while loop (just to see how many times it will iterate) it st

3条回答
  •  盖世英雄少女心
    2021-01-20 19:31

    The question why Iterator is important/introduced is simple:
    consider following example:
    List list = new ArrayList();
    list.add("Anurag");
    list.add("Soni");
    list.add("MMM");
    list.add("GKP");
    
    for(string s : list){
      if(s.equals(" Anurag")
      s.remove();
      System.out.println(s);
    }
    
    This will throw an exception-`Concurrent Modification exception` as you are trying to alter the structure of the data structure List before the iteration is completed.
    
    so you may use Iterator for the same purpose .
    Iterator iterator = List.iterator();
    
    while(iterator.hasNext()){
    String current = iterator.next();
    if(current=="Anurag"){
      iterator.remove();
    }else{
    System.out.println(current);
    }
    
    }
    OUTPUT:  Soni
             MMM
             GKP
    

提交回复
热议问题