Skip to main content

Generics - can't figure them out :-/

2 replies [Last post]
Joined: 2004-10-10

I'm trying to learn the new v1.5 features.
I can't figure out why this fails:

public abstract class Shape {

public class Rectangle extends Shape {
public void add( List<? extends Shape> shapes ) {
shapes.add( new Rectangle() );

To me, the code says: Here's a List that has in it instances of Shape or subclasses of Shape. To this list, add an instance of a Rectangle which is a subclass of Shape. Should have worked :-/


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2003-06-20

You could have said...

List list = ...;
list.add(new Rectangle());

because a Rectangle is a kind of shape.

Joined: 2003-06-10

List is a list of some type which extends Shape. For example, List would be an acceptable argument, but you clearly should not put a Rectangle in such a list.
So List guarantees that its content Object's all implement Shape, but does not allow you to put anything in because the real constraint may be much more specific.