Can anyone explain how the data are sorted in a TreeMap
automatically when we try to print the data stored in them?
views:
131answers:
3The items are already sorted - this is achieved through the use of a Red-Black Tree to store the items internally.
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.
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.