Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested List Iterator. Program doesn't terminates

Tags:

java

iterator

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?

like image 939
Pradeep Singh Avatar asked Jan 22 '26 05:01

Pradeep Singh


2 Answers

literate2.hasNext() always returns true. So while loop will never end.

like image 182
Mike Adamenko Avatar answered Jan 25 '26 00:01

Mike Adamenko


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.

like image 23
Avijit Karmakar Avatar answered Jan 25 '26 02:01

Avijit Karmakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!