Search code examples
javaloops

The loop doesn't work - only the first element repeats


Here is the code that reproduces the problem

var list = new ArrayList<String>();
list.add("Omni");
list.add("Okan");
var iter = list.iterator();
for (var item = iter.next(); iter.hasNext(); iter.next()) {
    System.out.println(item);
}

I tried this code and got Omni Omni instead of Onmi Okan. I tried also different sets of elements, but got the same problem - first element repeats list.size() times


Solution

  • Instead of

            for (var item = iter.next(); iter.hasNext(); iter.next()) {
                System.out.println(item);
            }
    

    You can use the following, but still not the best option:

            for (; iter.hasNext();) {
                System.out.println(iter.next());
            }
    

    Best option is to use a while loop like this:

            while (iter.hasNext()) {
                System.out.println(iter.next());
            }
    

    The problem is in your for loop.

    This is the structure of the for-loop

    for(initialization; exit condition; update variables)

    In your case, you used var item = iter.next() as the initializer, that means the item was initialized with the first value. After that value was printed, as the update variables part, you did iter.next(), this returned the next value. But you never stored it.

    After the update variables, it will check the exit condition. Since the 2nd value has been extracted, the iter.hasNext() will return false, so the for loop will exit. So, in your case, only ONE value was printed. 2nd value was just not stored in any variable. You could have done item = iter.next() as the update part, but still item would have been updated, but due to iter.hasNext() condition will return false just after update variables, it would not have been printed still.