| Author |
mock exam example
|
dolly shah
Ranch Hand
Joined: Jun 18, 2007
Posts: 383
|
|
Set set = new TreeSet(); set.add("F"); set.add("B"); set.add("E"); set.add("A"); int count=0; while(set.iterator().hasNext()){ System.out.print(set.iterator().next()+" "); count++; if(count==3)break; } How the result of above code is A A A. They have given the description "The program output will output A A A because when set.iterator() is called it returns a new iterator object. Each time the loop runs it creates and examines a new iterator object, but never advances beyond the first item. If we didn't break out of the loop after three iterations it would go on forever." But I am not getting it. Can anyone please explain?
|
SCJP-1.5<br />SCWCD-1.4
|
 |
Brian Cole
Author
Ranch Hand
Joined: Sep 20, 2005
Posts: 852
|
|
Does it make more sense if I rewrite it like this? Set set = new TreeSet(); set.add("F"); set.add("B"); set.add("E"); set.add("A"); int count=0; Iterator itA = set.iterator(); while(itA.hasNext()){ Iterator itB = set.iterator(); System.out.print(itB.next()+" "); count++; if(count==3)break; } The point is not only that itB is different from itA, but that itB is fleeting. It exists for one iteration of the loop, then is gone. A brand new itB gets created on the next iteration. [edit: transient -> fleeting (no reason to create confusion with the transient keyword)] [ August 30, 2007: Message edited by: Brian Cole ]
|
bitguru blog
|
 |
 |
|
|
subject: mock exam example
|
|
|