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.
Output:
Explanation:
lines 17 - 31
the CompareTo
method is
defined. It's used to sort the phones by price ascending.line 21
the sign >
is changed to <
, the phones will be sorted by
descending.
line 60
the collection of phones is sorted.
The sorting uses the CompareTo
method.
Explanation:
line 21
is
changed from >
to <
.
That's why the sorting is changed from ascending
to descending.
Output: