Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections question

 
Sriram Chintapalli
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
In a TreeSet/TreeMap are elements(keys) stored in sorted order or stored randomly and retrieved in sorted order?
thanks,
Sriram
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the API Spec for TreeSet:

This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.

And from the API Spec for TreeMap:

Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used.

So, in this case, it appears that the set or set of keys is stored and retrieved in a sorted order.
 
Sriram Chintapalli
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explanation Corey.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic