Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Enhanced For Loop never ending

This code is producing an endless loop:

        for (String element : friendSet) {
        resultNum ++;
        System.out.println("  Result # " + resultNum + " = " + element);
        System.out.print(" friendSet.size() = " + friendSet.size());
    }

friendSet.size() = 2923 but the results keep climbing to tens of thousands until I force the program to stop. For example:

friendSet.size() = 2923  Result # 7652 = Charlie
friendSet.size() = 2923  Result # 7653 = Jamie
friendSet.size() = 2923  Result # 7654 = Smith

What is going on?

like image 625
Qwertyfshag Avatar asked Jun 08 '26 09:06

Qwertyfshag


1 Answers

Behind the scenes: foreach loops in java just use the objects iterator.

Is friendSet some kind of custom iterable collection? if so, your iterator implementation is not correct.

like image 142
Colin D Avatar answered Jun 10 '26 19:06

Colin D



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!