开发者

Sorting technique followed by TreeMap?

Can anyone explain how the d开发者_Python百科ata are sorted in a TreeMap automatically when we try to print the data stored in them?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜