Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

while(ai.hasNext()){
    Objecttemp= ai.next();
    Stringao= temp.getImageUrl(ImageSize.MEGA);
    Stringan= temp.getName();

}

Solution 2:

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();
      ...
   }
}

Solution 3:

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.

Post a Comment for "Calling Next() Twice In Iterator Throws A Nosuchelementexception"