Below is my program.
public class NewClass {
public static void main(String[] args) {
List<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("Hundai");
cars.add("Polo");
Iterator<String> literate1 = cars.iterator();
while (literate1.hasNext()){
System.out.println(literate1.next());
literate1.remove();
Iterator<String> literate2 = cars.iterator();
while (literate2.hasNext()){
}
}
}
}
Output
Maruti
Just after printing this result, program doesn't terminates. Can you explain what is going on?
literate2.hasNext() always returns true. So while loop will never end.
Please check the below code. It will work.
List<String> cars = new ArrayList<String>();
cars.add("Maruti");
cars.add("Hundai");
cars.add("Polo");
Iterator<String> literate1 = cars.iterator();
while (literate1.hasNext()) {
System.out.println(literate1.next());
}
In your code, the inner while loop has the condition literate2.hasNext(). It's actually returning true all the time. For that reason, it's creating an infinite loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With