Nested list of iterators. The program does not end

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

      

The program does not terminate immediately after printing this result. Can you explain what's going on?

+3


source to share


3 answers


literate2.hasNext()

always returns true

. Thus, the cycle while

will never complete.



+2


source


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 a condition literate2.hasNext()

. It really comes back all the time. For this reason, it creates an endless loop.

+2


source


while (literate2.hasNext()){
}

      

An endless loop right there. Until you call next (), hasNext () will always return true if there are more elements.

+1


source







All Articles