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?
next() Return Value The next() function returns the next item from the iterator.
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. }
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With