简体   繁体   中英

why iterator.next() returns the same item every time?

I have this code:

    for (int j = 0; j < 7; j++) {
        if (failureCountAndDUrls.urls.iterator().hasNext()) {
            P p2 = new P().appendText("First "+min+" of "+failureCountAndDUrls.count+":");
            String id = failureCountAndDUrls.urls.iterator().next();
            }
        }

urls is a Set<String>

and yet .next(); returns the same item over and over. Even though there are 7 items

how can iterate all the items correctly?

The problem is you're creating a new iterator every time, and each new iterator has the same initial state.

Reuse the iterator instead.

Iterator<String> it = failureCountAndDUrls.urls.iterator();
for (int j = 0; j < 7; j++) {
    if (it.hasNext()) {
        P p2 = new P().appendText("First "+min+" of "+failureCountAndDUrls.count+":");
        String id = it.next();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM