ITEM 30: FAVOR GENERIC METHODS
137
Therefore, we can confidently suppress the unchecked cast warning generated by
this cast. Once we’ve done this, the code compiles without error or warning.
Here is a sample program that uses
our generic singleton as a
UnaryOpera-
tor
and a
UnaryOperator
. As usual, it contains no casts and
compiles without errors or warnings:
// Sample program to exercise generic singleton
public static void main(String[] args) {
String[] strings = { "jute", "hemp", "nylon" };
UnaryOperator sameString = identityFunction();
for (String s : strings)
System.out.println(sameString.apply(s));
Number[] numbers = { 1, 2.0, 3L };
UnaryOperator sameNumber = identityFunction();
for (Number n : numbers)
System.out.println(sameNumber.apply(n));
}
It is permissible, though relatively rare, for a type parameter to be bounded by
some expression involving that type parameter itself. This is what’s known as a
recursive type bound
. A common use of recursive type bounds is in connection
with the
Comparable
interface, which defines a type’s natural ordering (Item 14).
This interface is shown here:
public interface Comparable {
int compareTo(T o);
}
The type parameter
T
defines the type to which elements of the type implementing
Comparable
can be compared. In practice, nearly all types can be compared
only to elements of their own type. So, for example,
String
implements
Compa-
rable
,
Integer
implements
Comparable
, and so on.
Many methods take a collection of elements implementing
Comparable
to
sort it, search within it, calculate its minimum or maximum, and the like. To do
these things, it is required that every element in the collection be comparable to
every other element in it, in other words, that the elements of the list be
mutually
comparable
. Here is how to express that constraint:
Do'stlaringiz bilan baham: