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 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.
Comparable<T>
The interface Comparable<T>
declares a single instance method for comparing one object with another:
interface Comparable<T> { public int compareTo(T o); }
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 ...
Get Java Generics and Collections, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.