H
hiwa
Below is an excerpt from _Generics in the Java Programming Language_(aka Java
Generics Tutorial) by Gilad Bracha.
<quote>
There is, as usual, a price to be paid for the flexibility of using wildcards.
That price is that it is now illegal to write into shapes in the body of the method.
For instance, this is not allowed:
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // compile-time error!
}
You should be able to figure out why the code above is disallowed. The type of
the second parameter to shapes.add() is ? extends Shape - an unknown subtype of
Shape. Since we don t know what type it is, we don t know if it is a supertype
of Rectangle; it might or might not be such a supertype, so it isn t safe to pass
a Rectangle there.
</quote>
My question is: what should we do in order for the above List<? extends Shape>
type to be a mixin list of various(heterogeneous) shapes(circle, rectangle,
etc.)? In other words, we'd like to make the above shapes.add(0, new Rectangle())
call legal for the 1.5 compiler. How could we do that?
More lengthy excerpt:
http://homepage1.nifty.com/algafield/fromJavaGenericsTutorial.html
Generics Tutorial) by Gilad Bracha.
<quote>
There is, as usual, a price to be paid for the flexibility of using wildcards.
That price is that it is now illegal to write into shapes in the body of the method.
For instance, this is not allowed:
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // compile-time error!
}
You should be able to figure out why the code above is disallowed. The type of
the second parameter to shapes.add() is ? extends Shape - an unknown subtype of
Shape. Since we don t know what type it is, we don t know if it is a supertype
of Rectangle; it might or might not be such a supertype, so it isn t safe to pass
a Rectangle there.
</quote>
My question is: what should we do in order for the above List<? extends Shape>
type to be a mixin list of various(heterogeneous) shapes(circle, rectangle,
etc.)? In other words, we'd like to make the above shapes.add(0, new Rectangle())
call legal for the 1.5 compiler. How could we do that?
More lengthy excerpt:
http://homepage1.nifty.com/algafield/fromJavaGenericsTutorial.html