• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

mock exam example

 
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Author
Posts: 985
3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
What's that smell? Hey, sniff this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic