Issue
The following code gives an exception, however, I do not understand why.
List suits = ...;
List ranks = ...;
List sortedDeck = new ArrayList();
// BROKEN - throws NoSuchElementException!
for (Iterator i = suits.iterator(); i.hasNext(); )
for (Iterator j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(i.next(), j.next()));
The solution is apparently as follows:
// Fixed, though a bit ugly
for (Iterator i = suits.iterator(); i.hasNext(); ) {
Suit suit = (Suit) i.next();
for (Iterator j = ranks.iterator(); j.hasNext(); )
sortedDeck.add(new Card(suit, j.next()));
}
I understand why the solution works, but why doesn't the first example work?
Solution
Okay, I just understood why! It's simply because i.next()
ends up being called too many times due to the nested for-loop. It is only meant to access one suit, the same suit, for each group of 'j' iterations. Hence, the i.next()
is called outside the nested loop to prevent the suit from changing every single time.
Answered By - Grateful
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.