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.
Output:
Explanation:
lines 15 - 24
the compareTo
method is
defined. It's used to sort the phones by price ascending.line 16
the sign >
is changed to <
, the phones will be sorted by
descending.
line 59
the collection of phones is sorted.
The sorting uses the compareTo
method.
Explanation:
line 17
is
changed from >
to <
.
That's why the sorting is changed from ascending
to descending.ArrayList
to List
. The purpose of that is only to
prove that compareTo
method can be
applied to both ArrayList
and List
.
Output: