Have a Question?

If you have any question you can ask below or enter what you are looking for!

Difference between Comparator and Comparable in Java?

Difference between Comparator and Comparable in Java?
Difference between Comparator and Comparable in Java?

Difference between Comparator and Comparable in Java?

Difference between Comparator and Comparable in Java?

Comparator[I]

  • It is present in java.lang package and it contains only one method.
    • [highlight]compareTo()[/highlight];  
  • If we are depending on default natural sorting order then while adding the object into the TreeSet JVM will call compareTo() method. 
    • If default natural sorting order not available or if we are not satisfied with natural sorting order then we can go for customized sorting by using the comparator. 
  • Comparable meant for default natural sorting order whereas Comparator meant for customized sorting order

package com.java4us;

import java.util.TreeSet;

public class Test {

    public static void main(String[] args) {
        TreeSet t = new TreeSet();
        t.add("A");
        t.add("Z"); // --> "Z".compareTo("A") retrun +ve
        t.add("T"); // --> "T".compareTo("Z") retrun -ve
        System.out.println(t); // [A, T, Z]

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *