views:

131

answers:

3

Can anyone explain how the data are sorted in a TreeMap automatically when we try to print the data stored in them?

+4  A: 

The items are already sorted - this is achieved through the use of a Red-Black Tree to store the items internally.

teabot
+6  A: 

They aren't; TreeMap uses a red-black tree to manage the data, and this tree implicitly keeps the data sorted. All that the iterator has to do is to traverse the nodes.

Michael Borgwardt
thank, for the reference that you gave about red-black tree. According to this technique can you tell how the string values are arranged (i.e) how JVM decides ,a string is greater (or) smaller than the parent
Hari
@Hari: this is done using the 'compareTo' method of String
Fortega
More generally, the TreeMap class expects elements to implement the Comparable interface, to which that method belongs. Alternatively, you can pass an implementation of the Comparator interface to the TreeMap's constructor, which allows it to store objects that don't implement Comparable (or to use different sort orders).
Michael Borgwardt
@Fortega: how it is done in case of an object of a class say an Employee class that has details of an employee
Hari
@Hari: It looks as if your question is basically concerning sorting objects in any collection rather than just TreeSet. You should look up the docs for the Comparable and Comparator interfaces.
MAK
@MAK: i am not concerning about sorting objects in any collection..i just wanted to know how treemap sort the object in detail ... and got the answer... i didnt see michael's comment before posting mine..
Hari
+2  A: 

If the TreeMap stores objects that implement the Comparable interface (and String does) than it uses the .compareTo method to compare individual Strings and determine the sort order.

On the other hand you can provide a Comparator when constructing the TreeMap, and it will use that object to compare objects and determine the sort order. You can use Comparators to compare objects that do not implement Comparable, or enforce a different sorting strategy. For example, the String.compareTo method performs case-sensitive comparison, but you could provide the String.CASE_INSENSITIVE_ORDER comparator which would result in case-insensitive sorting.

romacafe