Chapter 3. Comparison and Bounds
Now that we have the basics, let’s look at some more advanced uses of
generics. This chapter describes the interfaces Comparable<T> and Comparator<T>, which are used to support
comparison on elements. These interfaces are useful, for
instance, if you want to find the maximum element of a collection or sort a
list. Along the way, we will introduce bounds on type variables, an important feature of generics that is
particularly useful in combination with the Comparable<T> interface.
Comparable
The interface Comparable<T>
contains a method that can be used to compare one object to
another:
interface Comparable<T> {
public int compareTo(T o);
}The compareTo method returns a
value that is negative, zero, or positive depending upon whether the
argument is less than, equal to, or greater than the given object. When a
class implements Comparable, the
ordering specified by this interface is called the natural
ordering for that class.
Typically, an object belonging to a class can only be compared with
an object belonging to the same class. For instance, Integer implements Comparable<Integer>:
Integer int0 = 0; Integer int1 = 1; assert int0.compareTo(int1) < 0;
The comparison returns a negative number, since 0 precedes 1
under numerical ordering. Similarly, String implements Comparable<String>:
String str0 = "zero"; String str1 = "one"; assert str0.compareTo(str1) > 0;
This comparison returns a positive number, since "zero" follows "one" under alphabetic ordering.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access