Here you can see the source code of the next()
method from java Iterator
. It looks something like this:
public E next() {
checkForComodification();
try {
int i = cursor;
E next = get(i);
lastRet = i;
cursor = i + 1;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
As you can see, if you are out of the array a NoSuchElementException
will be thrown. So calling next()
twice without checking before each call if elements are still available by using hasNext()
will have the behaviour you described.
Your while()
should be replaced with:
while(it.hasNext()) {
dummy.add((Card) it.next());
}
But if you really want the print-out as you have it, just change it to:
while (it.hasNext()) {
Card card = (Card)it.next();
System.out.println(card);
dummy.add(card);
}
The second approach is the better way to go when you need to use an object more than once in a method or loop if the method called may be expensive.