Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is 'natural ordering' in a TreeMap? [duplicate]

Tags:

java

treemap

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 ?

like image 504
John Threepwood Avatar asked Dec 30 '12 01:12

John Threepwood


Video Answer


1 Answers

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

like image 197
Brian Roach Avatar answered Sep 22 '22 15:09

Brian Roach