Java Reference
In-Depth Information
"eight" "five" "four" "one" "seven" "six" "three" "two"
Two additional versions of the
sort()
method that sort arrays of objects are parameterized methods.
These are for sorting arrays in which the order of elements is determined by an external comparator object.
The class type of the comparator object must implement the
java.util.Comparator<>
interface. One ad-
vantage of using an external comparator is that you can have several comparators that can impose different
orderings depending on the circumstances. For example, in some cases you might want to sort a name file
ordering by first name within second name. On other occasions you might want to sort by second name
within first name. You can't do this using the
Comparable<>
interface implemented by the class. The first
version of the
sort()
method that makes use of a comparator is:
<T>void sort(T[] array, Comparator<? super T> comparator)
This sorts all the elements of
array
using the comparator you pass as the second argument.
The second version of the s
ort()
method using a comparator is:
<T>void sort(T[] array, int fromIndex, int toIndex, Comparator<? super T>
comparator)
This sorts the elements of
array
from index position
fromIndex
up to but excluding the element at index
position
toIndex
.
The wildcard parameter to the
Comparator<>
type specifies that the type argument to the comparator can
be
T
or any superclass of
T
. This implies that the
sort()
method can sort an array of elements of type
T
us-
ing a
Comparator<>
object that can compare objects of type
T
or objects of any superclass of
T
. To put this
in a specific context, this means that you can use an object of type
Comparator<Person>
to sort an array of
objects of type
Manager
, where
Manager
is a subclass of
Person
.
The
Comparator<T>
interface declares two methods. First is the
compare()
method, which the
sort()
method uses for comparing elements of the array of type
T[]
. The method compares two objects of type
T
that are passed as arguments, so it's of the form:
int compare(T obj1, T obj2)
The method returns a negative integer, zero, or a positive integer, depending on whether
obj1
is less than,
equal to, or greater than
obj2
. The method throws a
ClassCastException
if the types of the argument you
pass are such that they cannot be compared by the comparator.
The second method in the
Comparator<T>
interface is
equals()
, which is used for comparing
Compar-
ator<>
objects for equality. The method is of the form:
boolean equals(Object comparator)
This compares the current
Comparator<>
object with another object of a type that also implements the
Comparator<>
interface that you pass as the argument. It returns a
boolean
value indicating whether the
current comparator object and the argument impose the same ordering on a collection of objects. I think it
would be a good idea to see how sorting using a
Comparator<>
object works in practice.