Skip to main content

Generics - can't figure them out :-/

2 replies [Last post]
randomalious
Offline
Joined: 2004-10-10
Points: 0

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 :-/

Confused,
-R.

Reply viewing options

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

You could have said...

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

because a Rectangle is a kind of shape.

mthornton
Offline
Joined: 2003-06-10
Points: 0

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.