Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

iterator

set

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?

like image 531
Elad Benda Avatar asked May 23 '15 15:05

Elad Benda


People also ask

What does iterator next () return?

next() Return Value The next() function returns the next item from the iterator.

How does iterator get next value?

iterator(); while ( iter. hasNext() ) { next = iter. next(); if ( current != null ) { // Passed the first iteration // Now you can use current and next, they both have values. }

How does iterator next work?

Think of next as a two-step process. First it gets the next item in the iterator, then it increments the pointer to point to the next item. So, when you create a new iterator, it is initialized to return the first item (index 0) in your list.

Does iterator next return the first element?

Once you obtain an iterator, it points to the first element of a collection; calling the next() function returns this element and moves the iterator position to the following element if it exists.


1 Answers

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();
    }
}
like image 167
Denys Séguret Avatar answered Sep 29 '22 06:09

Denys Séguret