Java Iterator question

Maximilian

Lifer
Feb 8, 2004
12,603
9
81
Iterator<Integer> anIterator = aSet.iterator();

Integer value1;
Integer value2;
Integer value3;

While (anIterator.hasNext())
{
value1 = anIterator.next();
value2 = anIterator.next();
value3 = anIterator.next();
}

Assuming that aSet has a total of 3 Integer elements am I correct in assuming that the while loop will only execute once? If it contained 6 elements the loop would execute twice yes?

Also would there be an infinite loop if the while loop had no .next() in it?
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
Correct on first 2 questions. Affirmative on the third, it would indeed loop forever without a call to next as the state wont change without it. Bare in mind if your set had 1 or 2 elements the code above would throw an exception on the next calls that are unguarded by the hasNext.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
Your code is safe if you can absolutely guarantee that there will always be a multiple of 3 items in your set. If not, you need to handle the case where it does not.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,295
3,920
75
Your code is safe if you can absolutely guarantee that there will always be a multiple of 3 items in your set. If not, you need to handle the case where it does not.

One way would be to catch a NoSuchElementException.