Java Reference
In-Depth Information
. . .
}
Purpose:
To define a generic method that depends on type variables
As with generic classes, you cannot replace type variables with primitive types. The
generic
print
method can print arrays of any type except the eight primitive types.
For example, you cannot use the generic
print
method to print an array of type
int[]
. That is not a major problem. Simply implement a
print(int[] a)
method in addition to the generic
print
method.
S
ELF
C
HECK
5.
Exactly what does the generic
print
method print when you pass an
array of
BankAccount
objects containing two bank accounts with
zero balances?
6.
Is the
getFirst
method of the
Pair
class a generic method?
17.4 Constraining Type Variables
It is often necessary to specify what types can be used in a generic class or method.
Consider a generic
min
method that finds the smallest element in an array list of
objects. How can you find the smallest element when you know nothing about the
element type? You need to have a mechanism for comparing array elements. One
solution is to require that the elements belong to a type that implements the
Comparable
interface. In this situation, we need to constrain the type variable.
public static <E
extends Comparable
> E min(E[] a)
{
E smallest = a[0];
for (int i = 1; i < a.length; i++)
if (a[i].compareTo(smallest) < 0) smallest =
a[i];
return smallest;
}
777
778
You can call
min
with a
String[]
array but not with a
Rectangle[]
arrayČthe
String
class implements
Comparable
, but
Rectangle
does not.