I think you mis-phrased that. It sounds like making the keys implement Comparator will work, but that's not true.
There are two possibilities:
1) The keys implement Comparable and are mutually comparable (i.e. an Integer and a String in one TreeMap would cause errors).
2) A separate Comparator is used; it has no connections with the keys other than the ability to compare them.
Seetharaman Venkatasamy wrote:TreeMap sorts objects depends on keys. for that the object should implements Comparator/Comparable
can you elaborate,
for example
what is natural in this case
i cant run this code i am getting class cast exception
info.inetsolv.Car cannot be cast to java.lang.Comparable
Basically, the "natural" order is the order defined by the Comparable interface. If the element doesn't support the Comparable interface, then it doesn't have a natural order, and if you try to use a TreeMap (without a Comparator), then you will get the cast exception.
Objects don't automatically have a natural order. A natural ordering is the one that make most sense given what the objects represent, but the computer doesn't know anything about that, so you have to tell it. And you tell it by implementing Comparable. The reason it already works for Integer and String is that the people who wrote those classes have already done this. But for your own classes, you have to.