Compareto Method

The compareTo method is used for sorting collection of class instances.

The method is also an implementation of the Comparable interface. It can be applied to both List and ArrayList.

Syntax

Interface implementation:

compareTo method:

Importing necessary package:

Sorting class collection via the compareTo method:

Examples

Ascending Sort

Output:

Explanation:

  • At lines 15 - 24 the compareTo method is defined. It's used to sort the phones by price ascending.
  • If at line 16 the sign > is changed to <, the phones will be sorted by descending.
  • At line 59 the collection of phones is sorted. The sorting uses the compareTo method.

Descending Sort

Explanation:

  • This example has the almost the same code as the ascending sort example
  • There are only 2 differences:
    • The comparision sign at line 17 is changed from > to <. That's why the sorting is changed from ascending to descending.
    • The collection is changed from ArrayList to List. The purpose of that is only to prove that compareTo method can be applied to both ArrayList and List.

Output: