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 lists.

Syntax

Interface implementation:

CompareTo method:

Sorting class collection via the compareTo method:

Examples

Ascending Sort

Output:

Explanation:

  • At lines 17 - 31 the CompareTo method is defined. It's used to sort the phones by price ascending.
  • If at line 21 the sign > is changed to <, the phones will be sorted by descending.
  • At line 60 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 is only 1 difference - the comparision sign at line 21 is changed from > to <. That's why the sorting is changed from ascending to descending.

Output: