Take the 2-minute tour ×

I just want someone to explain me one thing.According to Java documentation: Comparable interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo() method is referred to as its natural comparison method.Now we know class String implements Comparable ,then what happens when we create a String object? What is the natural ordering here??


class Com implements Comparator<String>{
public int compare<String>(String a,String b){
String s1=a; String s2=b;
return s2.compareTo(s1);

now suppose there is this snippet in Main() method:

TreeSet<String> ts=new TreeSet<String>(new Com());

Now when first C is being added there is no existing element in the TreeSet, so what happens?how is the comparison carried out then?

and when B is being added then what is happening. I would be great help if you tell me the process flow sequentially that happens here. Thank you in advance.

share|improve this question
You can simply take a look at the source code... No big mystery there. –  Thihara Dec 13 '12 at 11:11
Does your code compile? It seems to me you should have declared Com implements Comparator<String> - otherwise, you are not fulfilling the contract of Comparator (as it should default to Comparator<Object>; and you do not implement compareTo(Object a, Object b). –  tucuxi Dec 13 '12 at 11:14
Obviously, there is no comparison made for the first element. –  Marko Topolnik Dec 13 '12 at 11:14
Have you tried looking in the TreeMap sourcecode? Or even debug through it? –  Anders R. Bystrup Dec 13 '12 at 11:14
Would you tell me the process... –  Arijit Saha Dec 13 '12 at 11:15
show 1 more comment

2 Answers

This is snipped from the TreeMap source (JDK 1.6.0-30) (TreeSet is backed by a TreeMap unless another collection is explicitly chosen)

public V put(K key, V value) {
    Entry<K,V> t = root;
    if (t == null) {
        root = new Entry<K,V>(key, value, null);
        return null;

As you can see, if the map is empty (the root is null) the value is simply added. No comparison is done.

As for adding A and B, I'll leave that as an exercise for you, there's actually some good learning in there!


share|improve this answer
add comment

Your Answer


