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
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