Java Reference
In-Depth Information
dishes.add(d1);
dishes.add(d2);
dishes.add(d3);
Box.wrap(dishes);
The call to
wrap
passes in a
List<Dish<String>>
object, and the output looks like this:
Wrapping Dish@1389e4
Wrapping Dish@c20e24
Wrapping Dish@2e7263
If the syntax of
List<Dish<String>>
looks confusing, welcome to Java generics! Often
the syntax for generics requires the nesting of data types, which tends to result in code that
is not always intuitive. As we will see in the next section, the bounded generic types only
add another layer of complexity to this syntax.
Bounded Generic Types
A generic type parameter opens the door for any data type to be used as the generic type.
There might be situations where you want to use generics but also restrict the type used.
A
bounded parameter type
is a generic type that specifi es a bound for the generic. You can
specify a parent class for a generic type using the
extends
keyword, creating an upper-
bound generic, as the following example shows:
public class Hello<T extends List> { }
The previous declaration states that
T
is a generic type that must extend (or, in this case,
implement) the
List
interface. Using
extends
in a generic creates an upper bound on the
actual type used for the generic. For example, the following statements are valid for
the
Hello
class because
ArrayList
and
Stack
both implement
List
:
Hello<ArrayList> h1 = new Hello<ArrayList>();
Hello<Stack> h2 = new Hello<Stack>();
However, the following statement is not valid because a
HashMap
is not a
List
:
Hello<HashMap> h3 = new Hello<HashMap>(); //not valid
The compiler error looks like
Hello.java:7: type parameter java.util.HashMap is not within its bound
Hello<HashMap> h3 = new Hello<HashMap>();
Search WWH ::
Custom Search