Possible Duplicate:
How can I sort the keys of a Map in Java?
In class TreeMap
the Java API says:
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
What is meant by natural ordering ? A class used as key does not have to implement the Comparable
interface, but what ordering will be used instead ?
If you were to try this yourself you'd find that you cannot use a TreeMap
that has a K
that does not implement Comparable
(Unless you explicitly provide a Comparator
via the TreeMap
constructor).
public class App
{
public static void main( String[] args )
{
TreeMap<App,String> tm = new TreeMap<App,String>();
tm.put(new App(), "value");
}
}
Exception in thread "main" java.lang.ClassCastException: App cannot be cast to java.lang.Comparable
The javadoc for put()
states this explicitly:
Throws:
ClassCastException - if the specified key cannot be compared with the keys currently in the map
The link in javadocs for TreeMap for "Natural Ordering" takes you to the Comparable
interface