This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes mock exam example Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "mock exam example" Watch "mock exam example" New topic
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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: mock exam example
 
Similar Threads
LinkedHashSet
Why it returns a new iterator object
HashSet
HashSet question
Collections - the meaning of ORDERED