• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Q on collections framework: iteration order

 
blacksmith
Posts: 979
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

In Dan Chisolm's exam set the answer to the following question
(Comprehensive exam nr. 17, Question 24):


Suppose that you would like to create a new instance of a class
that implements the Set interface, and you would like the new
instance to be initialized with the elements of an existing Set.
If you would like the iteration order of the new Set to be the
same as that of the existing Set, then which concrete implementation
of the Set interface should be used for the new instance?



is LinkedHashSet, TreeSet is there as an option but NOT
included as part of the answer.

Since TreeSet is sorted, and sorting is a special kind of ordering,
I'd think the iterator should traverse both instances in the same way.

Am I overlooking something here?

Cheers,

Gian Franco
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Gian Franco,
Try the following:



When we iterate over the newly created LinkedHashSet we get the items in the same order as if we iterate over the HashSet. (But not the insertion order, that is not guaranteed to be kept by HashSet).

When we iterate over the new TreeSet we do not get the items in the same order as if we iterate over the HashSet. So choosing TreeSet is incorrect because it destroys the original iteration order.
 
Gian Franco
blacksmith
Posts: 979
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Barry,

Got it! I was under the wrong impression
that the two classes had to be the same.

Cheers

Gian Franco
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic