Java Reference
In-Depth Information
Comparator Sorting
The other version of the
sort
method in
Collections
does not require its elements to
implement
Comparable
. Instead, it uses a separate object of type
Comparator
to determine
the ordering:
public static <T> void sort(List<T> list, Comparator<? super T> c)
To use this version of
Collections.sort
, you need to write a class that implements the
generic
Comparator
interface, making sure the generic type of the
Comparator
is
T
or a
parent of
T
(based on the
<? super T>
in the method signature). The
Comparator
interface
declares the following method:
int compare(T o1, T o2)
Defi ne this method so that it returns
0
if
o1
equals
o2
, a positive number if
o1
is greater
than
o2
, and a negative number if
o1
is less than
o2
. The ordering is totally up to you, so
the logic can be anything you defi ne. For example, suppose we have the following class
named
Reverse
that implements the
Comparator
interface with an
Integer
generic type:
public class Reverse implements java.util.Comparator<Integer> {
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
The logic in
Reverse
is the opposite of the natural order of
Integer
. For example,
10
is
less than
5
using the logic of
Reverse
. To use this
Comparator
, create an instance and pass
it into the
sort
method along with the
List
object to be sorted. Study the following code
and see if you can determine its output:
List<Integer> list = new ArrayList<Integer>();
list.add(-5);
list.add(12);
list.add(7);
list.add(7);
list.add(30);
Collections.sort(list, new Reverse());
for(Integer i : list) {
System.out.println(i);
}
Search WWH ::
Custom Search