🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 8 )
October 20, 2025 - It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparable-interface-in-java-with-examples
Java Comparable Interface - GeeksforGeeks
It enables objects to be compared and sorted automatically without using an external Comparator. It contains the compareTo() method, which compares the current object with another object.
Published   March 11, 2022
🌐
Stack Overflow
stackoverflow.com › questions › 72160928 › how-to-implement-compareto-method-in-java-and-what-does-it-mean
comparable - How to implement compareTo method in Java and what does it mean - Stack Overflow
Furthermore, the compareTo method in your example uses the default implementation of comparing strings: This means that the strings are compared lexicographically (you can think of it as alphabetical).
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 7 )
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › lang › Comparable.html
Comparable (Java SE 11 & JDK 11 )
January 20, 2026 - It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.
🌐
Jenkov
jenkov.com › tutorials › java-collections › comparable.html
Java Comparable
The Java Comparable compareTo() method takes a single object as parameter and returns an int value. The int returned signal whether the object the compareTo() method is called on is larger than, equal to or smaller than the parameter object.
🌐
Java Programming
java-programming.mooc.fi › part-10 › 2-interface-comparable
The Comparable Interface - Java Programming
If a class implements the Comparable interface, objects created from that class can be sorted using Java's sorting algorithms. The compareTo method required by the Comparable interface receives as its parameter the object to which the "this" object is compared.
🌐
Oracle
docs.oracle.com › javase › 6 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 6)
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.
🌐
Reddit
reddit.com › r/javahelp › understanding the compareto() method
r/javahelp on Reddit: Understanding the compareTo() method
August 8, 2020 -

From what I have been reading, the compareTo() method returns the difference of the Unicode numerical values of two Strings when they are compared with each other. For instance, the String "hello" when compared with the String "hello" returns an integer value of zero, since they both have exactly the same Unicode characters in them. Based on my understanding of this method, "hello" should return zero when compared to "olleh", because the two Strings have the exact same Unicode characters in them. Instead, though, I am getting integer value of 7 returned to the console. Can someone break this down a bit for me to help me understand it better? Thanks in advance. Here is my code:

String str1 = "hello";
String str2 = "olleh";
System.out.println(str1.compareTo(str2)); // 7

Find elsewhere
🌐
Igor's Techno Club
igorstechnoclub.com › java-compareto
Java Comparable compareTo method: Natural Order Of Things | Igor's Techno Club
The compareTo method is a fundamental tool in Java for establishing order among objects. By implementing the Comparable interface and overriding compareTo, you can define custom ordering for your classes, enabling them to be easily sorted and ...
Top answer
1 of 9
24

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;
2 of 9
18

The compareTo method is described as follows:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Let's say we would like to compare Jedis by their age:

class Jedi implements Comparable<Jedi> {

    private final String name;
    private final int age;
        //...
}

Then if our Jedi is older than the provided one, you must return a positive, if they are the same age, you return 0, and if our Jedi is younger you return a negative.

public int compareTo(Jedi jedi){
    return this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}

By implementing the compareTo method (coming from the Comparable interface) your are defining what is called a natural order. All sorting methods in JDK will use this ordering by default.

There are ocassions in which you may want to base your comparision in other objects, and not on a primitive type. For instance, copare Jedis based on their names. In this case, if the objects being compared already implement Comparable then you can do the comparison using its compareTo method.

public int compareTo(Jedi jedi){
    return this.name.compareTo(jedi.getName());
}

It would be simpler in this case.

Now, if you inted to use both name and age as the comparison criteria then you have to decide your oder of comparison, what has precedence. For instance, if two Jedis are named the same, then you can use their age to decide which goes first and which goes second.

public int compareTo(Jedi jedi){
    int result = this.name.compareTo(jedi.getName());
    if(result == 0){
        result = this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
    }
    return result;
}

If you had an array of Jedis

Jedi[] jediAcademy = {new Jedi("Obiwan",80), new Jedi("Anakin", 30), ..}

All you have to do is to ask to the class java.util.Arrays to use its sort method.

Arrays.sort(jediAcademy);

This Arrays.sort method will use your compareTo method to sort the objects one by one.

🌐
Baeldung
baeldung.com › home › java › core java › guide to implementing the compareto method
Guide to Implementing the compareTo Method - Java
May 29, 2025 - TreeMap and TreeSet are two implementations from the Java Collections Framework that assist us with the automatic sorting of their elements. We may use objects that implement the Comparable interface in a sorted map or as elements in a sorted set. Let’s look at an example of a custom class that compares players based on the number of goals they have scored: @Override public int compareTo(FootballPlayer anotherPlayer) { return Integer.compare(this.goalsScored, anotherPlayer.goalsScored); }
🌐
Reddit
reddit.com › r/learnjava › i need some help understanding comparable interface
r/learnjava on Reddit: I need some help understanding Comparable interface
October 17, 2017 -

I'm struggling to understand why we need to use compareTo for comparing things when I can just create a method that does the same thing. What I understand so far is that Interfaces can hold abstract methods without implementation, and once you implement that interface on a class you have to override the method from the interface and write the implementation. What I don't understand is what is significant about (implements Comparable<T>) if all I'm gonna do is override compareTo method so it returns 1 if larger, -1 if smaller or 0 if equal.

🌐
Tutorialspoint
tutorialspoint.com › java › number_compareto.htm
Java - compareTo() Method
Java Vs. C++ ... The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc. However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type. public ...
🌐
Zero To Mastery
zerotomastery.io › blog › java-compareto-method
Beginner's Guide To compareto In Java (With Code Examples) | Zero To Mastery
And so to make your objects sortable, you need to tell Java how to compare them by implementing the Comparable<T> interface and define a compareTo method.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › lang › Comparable.html
Comparable (Java SE 17 & JDK 17)
January 20, 2026 - This 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.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Implementing compareTo
Instead, Object appears, along with a related cast operation · Boolean objects must be treated differently from other wrapper classes, since Boolean did not implement Comparable until JDK 1.5. Example: import java.util.*; import java.io.*; public final class AccountOld implements Comparable { public AccountOld ( String aFirstName, String aLastName, int aAccountNumber, int aBalance, boolean aIsNewAccount, AccountType aAccountType ) { //..parameter validations elided fFirstName = aFirstName; fLastName = aLastName; fAccountNumber = aAccountNumber; fBalance = aBalance; fIsNewAccount = aIsNewAccount; fAccountType = aAccountType; } /** * @param aThat is a non-null AccountOld.
🌐
Java
download.java.net › java › early_access › valhalla › docs › api › java.base › java › lang › Comparable.html
Comparable (Java SE 23 & JDK 23 [build 1])
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.
🌐
DZone
dzone.com › coding › languages › java comparable interface in five minutes
Java Comparable Interface in Five Minutes
April 6, 2017 - The compareTo() method works by returning an int value that is either positive, negative, or zero. It compares the object by making the call to the object that is the argument. A negative number means that the object making the call is “less” ...