[java] What is the difference between compare() and compareTo()?

What is the difference between Java's compare() and compareTo() methods? Do those methods give same answer?

This question is related to java

The answer is


The methods do not have to give the same answers. That depends on which objects/classes you call them.

If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.

If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.


Use Comparable interface for sorting on the basis of more than one value like age,name,dept_name... For one value use Comparator interface


compareTo() is called on one object, to compare it to another object. compare() is called on some object to compare two other objects.

The difference is where the logic that does actual comparison is defined.


compareTo() is from the Comparable interface.

compare() is from the Comparator interface.

Both methods do the same thing, but each interface is used in a slightly different context.

The Comparable interface is used to impose a natural ordering on the objects of the implementing class. The compareTo() method is called the natural comparison method. The Comparator interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.


When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.

When you want to write a Util class which compares two other classes you can implement the Comparator class.


The methods do not have to give the same answers. That depends on which objects/classes you call them.

If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.

If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.


Comparable interface contains a method called compareTo(obj) which takes only one argument and it compares itself with another instance or objects of the same class.

Comparator interface contains a method called compare(obj1,obj2) which takes two arguments and it compares the value of two objects from the same or different classes.


When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.

When you want to write a Util class which compares two other classes you can implement the Comparator class.


The methods do not have to give the same answers. That depends on which objects/classes you call them.

If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.

If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.


Important Answar
String name;
int roll;

public int compare(Object obj1,Object obj2) { // For Comparator interface
    return obj1.compareTo(obj1);
}

public int compareTo(Object obj1) { // For Comparable Interface
    return obj1.compareTo(obj);
}

Here in return obj1.compareTo(obj1) or return obj1.compareTo(obj) statement only take Object; primitive is not allowed. For Example

name.compareTo(obj1.getName()) // Correct Statement.

But

roll.compareTo(obj1.getRoll()) 
// Wrong Statement Compile Time Error Because roll 
// is not an Object Type, it is primitive type.

name is String Object so it worked. If you want to sort roll number of student than use below code.

public int compareTo(Object obj1) { // For Comparable Interface
    Student s = (Student) obj1;
    return rollno - s.getRollno();
}  

or

public int compare(Object obj1,Object obj2) { // For Comparator interface
    Student s1 = (Student) obj1;
    Student s2 = (Student) obj2;
    return s1.getRollno() - s2.getRollno();
}  

compareTo() is called on one object, to compare it to another object. compare() is called on some object to compare two other objects.

The difference is where the logic that does actual comparison is defined.


Use Comparable interface for sorting on the basis of more than one value like age,name,dept_name... For one value use Comparator interface


The main difference is in the use of the interfaces:

Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.


When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.

When you want to write a Util class which compares two other classes you can implement the Comparator class.


The relationship of the object having this method and its collaborators is different.

compareTo() is a method of the interface Comparable, so it is used to compare THIS instance to another one.

compare() is a method of the interface Comparator, so it is used to compare two different instances of another class with each other.

If you will, implementing Comparable means that instances of the class can be easily compared.
Implementing Comparator means, that instances are suited to compare different objects (of other classes).


Using Comparator, we can have n number of comparison logic written for a class.

E.g.

For a Car Class

We can have a Comparator class to compare based on car model number. We can also have a Comparator class to compare based on car model year.

Car Class

public class Car  {

    int modelNo;

    int modelYear;

    public int getModelNo() {
        return modelNo;
    }

    public void setModelNo(int modelNo) {
        this.modelNo = modelNo;
    }

    public int getModelYear() {
        return modelYear;
    }

    public void setModelYear(int modelYear) {
        this.modelYear = modelYear;
    }

}

Comparator #1 based on Model No

public class CarModelNoCompartor implements Comparator<Car>{

    public int compare(Car o1, Car o2) {

        return o1.getModelNo() - o2.getModelNo();
    }

}

Comparator #2 based on Model Year

public class CarModelYearComparator implements Comparator<Car> {

    public int compare(Car o1, Car o2) {

        return o1.getModelYear() - o2.getModelYear();
    }

}

But this is not possible with the case of Comparable interface.

In case of Comparable interface, we can have only one logic in compareTo() method.


The methods do not have to give the same answers. That depends on which objects/classes you call them.

If you are implementing your own classes which you know you want to compare at some stage, you may have them implement the Comparable interface and implement the compareTo() method accordingly.

If you are using some classes from an API which do not implement the Comparable interface, but you still want to compare them. I.e. for sorting. You may create your own class which implements the Comparator interface and in its compare() method you implement the logic.


Similarities:
Both are custom ways to compare two objects.
Both return an int describing the relationship between two objects.

Differences: The method compare() is a method that you are obligated to implement if you implement the Comparator interface. It allows you to pass two objects into the method and it returns an int describing their relationship.

Comparator comp = new MyComparator();
int result = comp.compare(object1, object2);

The method compareTo() is a method that you are obligated to implement if you implement the Comparable interface. It allows an object to be compared to objects of similar type.

String s = "hi";
int result = s.compareTo("bye");

Summary:
Basically they are two different ways to compare things.


Using Comparator, we can have n number of comparison logic written for a class.

E.g.

For a Car Class

We can have a Comparator class to compare based on car model number. We can also have a Comparator class to compare based on car model year.

Car Class

public class Car  {

    int modelNo;

    int modelYear;

    public int getModelNo() {
        return modelNo;
    }

    public void setModelNo(int modelNo) {
        this.modelNo = modelNo;
    }

    public int getModelYear() {
        return modelYear;
    }

    public void setModelYear(int modelYear) {
        this.modelYear = modelYear;
    }

}

Comparator #1 based on Model No

public class CarModelNoCompartor implements Comparator<Car>{

    public int compare(Car o1, Car o2) {

        return o1.getModelNo() - o2.getModelNo();
    }

}

Comparator #2 based on Model Year

public class CarModelYearComparator implements Comparator<Car> {

    public int compare(Car o1, Car o2) {

        return o1.getModelYear() - o2.getModelYear();
    }

}

But this is not possible with the case of Comparable interface.

In case of Comparable interface, we can have only one logic in compareTo() method.


The relationship of the object having this method and its collaborators is different.

compareTo() is a method of the interface Comparable, so it is used to compare THIS instance to another one.

compare() is a method of the interface Comparator, so it is used to compare two different instances of another class with each other.

If you will, implementing Comparable means that instances of the class can be easily compared.
Implementing Comparator means, that instances are suited to compare different objects (of other classes).


Employee Table
Name, DoB, Salary
Tomas , 2/10/1982, 300
Daniel , 3/11/1990, 400
Kwame , 2/10/1998, 520

The Comparable interface allows you to sort a list of objects eg Employees with reference to one primary field – for instance, you could sort by name or by salary with the CompareTo() method

emp1.getName().compareTo(emp2.getName())

A more flexible interface for such requirements is provided by the Comparator interface, whose only method is compare()

public interface Comparator<Employee> {
 int compare(Employee obj1, Employee obj2);
}

Sample code

public class NameComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {
     // some conditions here
        return e1.getName().compareTo(e2.getName()); // returns 1 since (T)omas > (D)an 
    return e1.getSalary().compareTo(e2.getSalary()); // returns -1 since 400 > 300
}

}


There is a technical aspect that should be emphasized, too. Say you need comparison behavior parameterization from a client class, and you are wondering whether to use Comparable or Comparator for a method like this:

class Pokemon {
    int healthPoints;
    int attackDamage;
    public void battle (Comparable<Pokemon> comparable, Pokemon opponent) {
        if (comparable.compareTo(opponent) > 0) { //comparable needs to, but cannot, access this.healthPoints for example
            System.out.println("battle won");
        } else {
            System.out.println("battle lost");
        }
    }
}

comparable would a lambda or an object, and there is no way for comparable to access the fields of this Pokemon. (In a lambda, this refers to the outer class instance in the lambda's scope, as defined in the program text.) So this doesn't fly, and we have to use a Comparator with two arguments.


The relationship of the object having this method and its collaborators is different.

compareTo() is a method of the interface Comparable, so it is used to compare THIS instance to another one.

compare() is a method of the interface Comparator, so it is used to compare two different instances of another class with each other.

If you will, implementing Comparable means that instances of the class can be easily compared.
Implementing Comparator means, that instances are suited to compare different objects (of other classes).


compareTo() is called on one object, to compare it to another object. compare() is called on some object to compare two other objects.

The difference is where the logic that does actual comparison is defined.


compareTo() is from the Comparable interface.

compare() is from the Comparator interface.

Both methods do the same thing, but each interface is used in a slightly different context.

The Comparable interface is used to impose a natural ordering on the objects of the implementing class. The compareTo() method is called the natural comparison method. The Comparator interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.


The main difference is in the use of the interfaces:

Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.


There is a technical aspect that should be emphasized, too. Say you need comparison behavior parameterization from a client class, and you are wondering whether to use Comparable or Comparator for a method like this:

class Pokemon {
    int healthPoints;
    int attackDamage;
    public void battle (Comparable<Pokemon> comparable, Pokemon opponent) {
        if (comparable.compareTo(opponent) > 0) { //comparable needs to, but cannot, access this.healthPoints for example
            System.out.println("battle won");
        } else {
            System.out.println("battle lost");
        }
    }
}

comparable would a lambda or an object, and there is no way for comparable to access the fields of this Pokemon. (In a lambda, this refers to the outer class instance in the lambda's scope, as defined in the program text.) So this doesn't fly, and we have to use a Comparator with two arguments.


The main difference is in the use of the interfaces:

Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.


Comparable interface contains a method called compareTo(obj) which takes only one argument and it compares itself with another instance or objects of the same class.

Comparator interface contains a method called compare(obj1,obj2) which takes two arguments and it compares the value of two objects from the same or different classes.


When you want to sort a List which include the Object Foo, the Foo class has to implement the Comparable interface, because the sort methode of the List is using this methode.

When you want to write a Util class which compares two other classes you can implement the Comparator class.


Similarities:
Both are custom ways to compare two objects.
Both return an int describing the relationship between two objects.

Differences: The method compare() is a method that you are obligated to implement if you implement the Comparator interface. It allows you to pass two objects into the method and it returns an int describing their relationship.

Comparator comp = new MyComparator();
int result = comp.compare(object1, object2);

The method compareTo() is a method that you are obligated to implement if you implement the Comparable interface. It allows an object to be compared to objects of similar type.

String s = "hi";
int result = s.compareTo("bye");

Summary:
Basically they are two different ways to compare things.


One more point:

  • compareTo() is from the Comparable interface and compare() is from the Comparator interface.
  • Comparable is used to define a default ordering for objects within a class while Comparator is used to define a custom ordering to be passed to a method.

compareTo() is called on one object, to compare it to another object. compare() is called on some object to compare two other objects.

The difference is where the logic that does actual comparison is defined.


The relationship of the object having this method and its collaborators is different.

compareTo() is a method of the interface Comparable, so it is used to compare THIS instance to another one.

compare() is a method of the interface Comparator, so it is used to compare two different instances of another class with each other.

If you will, implementing Comparable means that instances of the class can be easily compared.
Implementing Comparator means, that instances are suited to compare different objects (of other classes).


The main difference is in the use of the interfaces:

Comparable (which has compareTo()) requires the objects to be compared (in order to use a TreeMap, or to sort a list) to implement that interface. But what if the class does not implement Comparable and you can't change it because it's part of a 3rd party library? Then you have to implement a Comparator, which is a bit less convenient to use.


Similarities:
Both are custom ways to compare two objects.
Both return an int describing the relationship between two objects.

Differences: The method compare() is a method that you are obligated to implement if you implement the Comparator interface. It allows you to pass two objects into the method and it returns an int describing their relationship.

Comparator comp = new MyComparator();
int result = comp.compare(object1, object2);

The method compareTo() is a method that you are obligated to implement if you implement the Comparable interface. It allows an object to be compared to objects of similar type.

String s = "hi";
int result = s.compareTo("bye");

Summary:
Basically they are two different ways to compare things.


compareTo() is from the Comparable interface.

compare() is from the Comparator interface.

Both methods do the same thing, but each interface is used in a slightly different context.

The Comparable interface is used to impose a natural ordering on the objects of the implementing class. The compareTo() method is called the natural comparison method. The Comparator interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.


Employee Table
Name, DoB, Salary
Tomas , 2/10/1982, 300
Daniel , 3/11/1990, 400
Kwame , 2/10/1998, 520

The Comparable interface allows you to sort a list of objects eg Employees with reference to one primary field – for instance, you could sort by name or by salary with the CompareTo() method

emp1.getName().compareTo(emp2.getName())

A more flexible interface for such requirements is provided by the Comparator interface, whose only method is compare()

public interface Comparator<Employee> {
 int compare(Employee obj1, Employee obj2);
}

Sample code

public class NameComparator implements Comparator<Employee> {

public int compare(Employee e1, Employee e2) {
     // some conditions here
        return e1.getName().compareTo(e2.getName()); // returns 1 since (T)omas > (D)an 
    return e1.getSalary().compareTo(e2.getSalary()); // returns -1 since 400 > 300
}

}


compareTo(T object)

comes from the java.lang.Comparable interface, implemented to compare this object with another to give a negative int value for this object being less than, 0 for equals, or positive value for greater than the other. This is the more convenient compare method, but must be implemented in every class you want to compare.

compare(T obj1, T obj2)

comes from the java.util.Comparator interface, implemented in a separate class that compares another class's objects to give a negative int value for the first object being less than, 0 for equals, or positive value for greater than the second object. It is needed when you cannot make a class implement compareTo() because it is not modifiable. It is also used when you want different ways to compare objects, not just one (such as by name or age).


compareTo(T object)

comes from the java.lang.Comparable interface, implemented to compare this object with another to give a negative int value for this object being less than, 0 for equals, or positive value for greater than the other. This is the more convenient compare method, but must be implemented in every class you want to compare.

compare(T obj1, T obj2)

comes from the java.util.Comparator interface, implemented in a separate class that compares another class's objects to give a negative int value for the first object being less than, 0 for equals, or positive value for greater than the second object. It is needed when you cannot make a class implement compareTo() because it is not modifiable. It is also used when you want different ways to compare objects, not just one (such as by name or age).


Similarities:
Both are custom ways to compare two objects.
Both return an int describing the relationship between two objects.

Differences: The method compare() is a method that you are obligated to implement if you implement the Comparator interface. It allows you to pass two objects into the method and it returns an int describing their relationship.

Comparator comp = new MyComparator();
int result = comp.compare(object1, object2);

The method compareTo() is a method that you are obligated to implement if you implement the Comparable interface. It allows an object to be compared to objects of similar type.

String s = "hi";
int result = s.compareTo("bye");

Summary:
Basically they are two different ways to compare things.


compareTo() is from the Comparable interface.

compare() is from the Comparator interface.

Both methods do the same thing, but each interface is used in a slightly different context.

The Comparable interface is used to impose a natural ordering on the objects of the implementing class. The compareTo() method is called the natural comparison method. The Comparator interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.


Important Answar
String name;
int roll;

public int compare(Object obj1,Object obj2) { // For Comparator interface
    return obj1.compareTo(obj1);
}

public int compareTo(Object obj1) { // For Comparable Interface
    return obj1.compareTo(obj);
}

Here in return obj1.compareTo(obj1) or return obj1.compareTo(obj) statement only take Object; primitive is not allowed. For Example

name.compareTo(obj1.getName()) // Correct Statement.

But

roll.compareTo(obj1.getRoll()) 
// Wrong Statement Compile Time Error Because roll 
// is not an Object Type, it is primitive type.

name is String Object so it worked. If you want to sort roll number of student than use below code.

public int compareTo(Object obj1) { // For Comparable Interface
    Student s = (Student) obj1;
    return rollno - s.getRollno();
}  

or

public int compare(Object obj1,Object obj2) { // For Comparator interface
    Student s1 = (Student) obj1;
    Student s2 = (Student) obj2;
    return s1.getRollno() - s2.getRollno();
}  

One more point:

  • compareTo() is from the Comparable interface and compare() is from the Comparator interface.
  • Comparable is used to define a default ordering for objects within a class while Comparator is used to define a custom ordering to be passed to a method.