Tutorial :What is a practical application of Java's compareTo method?


In the Java textbook I'm learning from, it says that this uses "lexicographic ordering" to return an integer. I understand how it works, but what is a specific way this is used in programming?


All of the built-in sorting methods use it when sorting non-primitives


Let's say you wanted to sort glasses of water, the objects themselves are called Glass.

Now let's say that a Glass can have a height and an amount of water that it holds.

Now let's say you wanted to compare two Glasses. How would you do it?

I'd do this by overriding the compareTo method. In that method I would say that if two glasses are of the same height and have the same amount of water in them, then they are equal. Obviously you'd want logic for greater than or less than, but you get the idea.


If you have a custom class that is going to end up in a collection that needs to be sorted, this is where you will put all of your custom logic determining what order the object will be in in relation to the object you're comparing to.


It can sort Strings, for example. It will return a value < 0, = 0, or > 0 depending on whether one String precedes another in alphabetical order.


compareTo() is the standard way to represent a default total ordering on non-primitive types in Java.

The advantage of returning an integer is that it only needs to be called once to distinguish the three cases <, == and >. (The alternative approach of for example using methods equals() and greaterThan() would need two calls.)

It can be used anywhere where a total ordering is needed. The most important are:

  • For implementations of sorted collections like TreeSet and TreeMap (these use red black trees).

  • For explicitly sorting collections.

  • In other algorithms, e.g. ranges of user-defined number types like rationals.


compareTo compares values and returns an int which tells if the values compare less than, equal, or greater than.

If your class objects have a natural order, implement the Comparable interface and define this method. All Java classes that have a natural ordering implement this (String, Double, BigInteger, ...).

The compareTo method needs to satisfy the following conditions:

  • x.compareTo(y) is the opposite sign of y.compareTo(x) if x & y are different
  • If x.compareTo(y) > 0, and y.compareTo(z) > 0, then x.compareTo(z) > 0.
  • Consistency with equals() is recommended.



It's most common use is as a comparison function when sorting a list of strings. One call to compareTo tells you whether one string comes before another, after another, or is the same as another string.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »