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 of objects by their elements. These interfaces are useful if, for instance, you want to find the maximum element of a collection or to 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.
Note
The examples for this chapter can be found at:
https://github.com/MauriceNaftalin/JGC_2e_Book_Code/tree/main/src/main/java/org/jgcbook/chapter03
Comparable
The interface Comparable<T> declares a single instance method for comparing one object with another:
interface Comparable<T> {
public int compareTo(T other);
}
The compareTo method returns an integer value that is negative, zero, or positive depending upon whether the receiver—this object—is less than, equal to, or greater than the argument. 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;
This comparison returns a negative number, since 0
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