Java Reference
In-Depth Information
is ascending, your
compare()
method establishes a descending sequence. If the surnames are equal, the
order is determined by the first names, again inverting the sign of the value returned by the
compareTo()
method to maintain descending sequence. Of course, you could have coded this method by switching the
arguments,
person1
and
person2
, instead of reversing the sign:
public int compare(Person person1, Person person2) {
int result = person2.getSurname().compareTo(person1.getSurname());
return result == 0 ?
person2.getFirstName().compareTo(person1.getFirstName()) : result;
}
This would establish a descending sequence for
Person
objects.
You call the
sort()
method a second time with the statement:
Arrays.sort(authors); // Sort using
compareTo() method
Because you have not supplied a comparator, the
sort()
method expects the class type of the elements
to be sorted to have implemented the
Comparable<>
interface. Fortunately your
Person
class does, so
the authors get sorted. This time the result is in ascending sequence because that's what the
compareTo()
method establishes.
Searching Arrays
The static
binarySearch()
method in the
Arrays
class searches the elements of a sorted array for a given
value using the binary search algorithm. This works only if the elements of the array are in ascending se-
quence, so if they are not, you should call the
sort()
method before calling
binarySearch()
. The binary
search algorithm works by repeatedly subdividing the sequence of elements to find the target element value,
as illustrated in
Figure 15-1
.