java - Iterating over collections -


the following code gives exception, however, not understand why.

list suits = ...; list ranks = ...; list sorteddeck = new arraylist();  // broken - throws nosuchelementexception! (iterator = suits.iterator(); i.hasnext(); )     (iterator j = ranks.iterator(); j.hasnext(); )         sorteddeck.add(new card(i.next(), j.next())); 

the solution apparently follows.

// fixed, though bit ugly (iterator = suits.iterator(); i.hasnext(); ) {     suit suit = (suit) i.next();     (iterator j = ranks.iterator(); j.hasnext(); )         sorteddeck.add(new card(suit, j.next())); } 

although, understand why solution works, don't quite understand why first example doesn't. can elaborate on please. appreciated.

okay, understood why! it's because i.next() ends being called many times due nested for-loop. meant access 1 suit, same suit, each group of 'j' iterations. hence, i.next() called outside nested loop prevent suit changing every single time.


Comments