Java Reference
In-Depth Information
1
public static <AnyType>
2
boolean contains( AnyType [ ] arr, AnyType x )
3
{
4
for( AnyType val : arr )
5
if( x.equals( val ) )
6
return true;
7
8
return false;
9
}
figure 4.34
Generic static method
to search an array
The generic method looks much like the generic class in that the type
parameter list uses the same syntax. The type parameters in a generic method
precede the return type.
4.7.4
type bounds
Suppose we want to write a
findMax
routine. Consider the code in Figure 4.35.
This code cannot work because the compiler cannot prove that the call to
compareTo
at line 6 is valid;
compareTo
is guaranteed to exist only if
AnyType
is
Comparable
. We can solve this problem by using a
type bound
. The type bound
is specified inside the angle brackets
<>
, and it specifies properties that the
parameter types must have. A naive attempt is to rewrite the signature as
The type bound is
specified inside the
angle brackets
<>
.
public static <AnyType extends Comparable> ...
This is naive because as we know, the
Comparable
interface is now generic.
Although this code would compile, a better attempt would be
public static <AnyType extends Comparable<AnyType>> ...
However, this attempt is not satisfactory. To see the problem, suppose
Shape
implements
Comparable<Shape>
. Suppose
Square
extends
Shape
. Then all
figure 4.35
Generic static method
to find largest element
in an array that does
not work
1
public static <AnyType> AnyType findMax( AnyType [ ] a )
2
{
3
int maxIndex = 0;
4
5
for( int i = 1; i < a.length; i++ )
6
if( a[ i ].compareTo( a[ maxIndex ] ) > 0 )
7
maxIndex = i;
8
9
return a[ maxIndex ];
10
}
Search WWH ::
Custom Search