adneal
adneal

Reputation: 30814

Calling next() twice in Iterator throws a NoSuchElementException

I'm retrieving several values from a sequence, but need to do so twice for a separate set of values coming from the same sequence. If I call one or the other, everything comes back to me correctly, but calling next() twice results in a NoSuchElementException. After reading about this online, I've gathered that after calling next() once, any other time after that calling it again will basically return the iterator false. How do you get two separate sets of data from the same Collection?

while (ai.hasNext()) {
   String ao = ai.next().getImageURL(ImageSize.MEGA);
   String an= ai.next().getName();
}

Upvotes: 4

Views: 7202

Answers (3)

Nigel
Nigel

Reputation: 161

You can store next() as a temporary variable. Replace Object in the following code with the datatype you are iterating through.

while(ai.hasNext()){
    Object temp = ai.next();
    String ao = temp.getImageUrl(ImageSize.MEGA);
    String an = temp.getName();

}

Upvotes: 8

Bruno Silva
Bruno Silva

Reputation: 3097

If you are not sure your list has an even number of elements, you just need to add if (ai.hasNext()) before your 2nd call to next().

while (ai.hasNext()) {
   String ao = ai.next().getImageURL(ImageSize.MEGA);
   if (ai.hasNext())) {
      String an= ai.next().getName();
      ...
   }
}

Upvotes: 2

Deco
Deco

Reputation: 3321

You will run into this error when your collection has an uneven number of elements, you shouldn't call next() twice without checking there is something there; you're essentially breaking the point of the while loop by doing that.

next() will work as long as there's something in the collection to get. This is a code example that works perfectly fine on JDK1.6.0_23

    Collection<String> aCollection = new ArrayList<String>();

    aCollection.add("1");
    aCollection.add("2");

    Iterator<String> i = aCollection.iterator();

    String firstString = null;
    String secondString = null;

    while (i.hasNext()) {
        firstString = (String) i.next();
        secondString = (String) i.next();
    }

    System.out.println(firstString);
    System.out.println(secondString);

If you add another String into the Collection you will end up with a NoSuchElementException as you have described. You either need to have two seperate iterators over the same data, or you need to put another check within your while loop to check that there's still something left in the collection before trying to get it out.

Upvotes: 0

Related Questions