Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading