Java Reference
In-Depth Information
figure 4.33
totalArea method
revised with wildcards
that works if passed
an ArrayList<Square>
1 public static double totalArea( ArrayList<? extends Shape> arr )
2 {
3 double total = 0;
4
5 for( Shape s : arr )
6 if( s != null )
7 total += s.area( );
8
9 return total;
10 }
What we are left with is that generics (and the generic collections) are
not covariant (which makes sense) but arrays are. Without additional syntax,
users would tend to avoid collections because the lack of covariance makes
the code less flexible.
Java 5 makes up for this with wildcards . Wildcards are used to express
subclasses (or superclasses) of parameter types. Figure 4.33 illustrates the
use of wildcards with a bound to write a totalArea method that takes as
parameter an ArrayList<T> , where T IS-A Shape . Thus, ArrayList<Shape> and
ArrayList<Square> are both acceptable parameters. Wildcards can also be
used without a bound (in which case extends Object is presumed) or with
super instead of extends (to express superclass rather than subclass); there
are also some other syntax uses that we do not discuss here.
Wildcards are used
to express sub-
classes (or
superclasses) of
parameter types.
4.7.3 generic static methods
In some sense, the totalArea method in Figure 4.33 is generic, since it works
for different types. But there is no specific type parameter list, as was done in
the GenericMemoryCell class declaration. Sometimes the specific type is impor-
tant perhaps because one of the following reasons apply:
1.
The type is used as the return type
The generic
method looks much
like the generic
class in that the
type parameter list
uses the same syn-
tax. The type list in
a generic method
precedes the return
type.
2.
The type is used in more than one parameter type
3.
The type is used to declare a local variable
If so, then an explicit generic method with type parameters must be declared.
For instance, Figure 4.34 illustrates a generic static method that per-
forms a sequential search for value x in array arr . By using a generic
method instead of a nongeneric method that uses Object as the parameter
types, we can get compile-time errors if searching for an Apple in an array
of Shape s.
 
Search WWH ::




Custom Search