0

Can Some one please explain why the line no. 12 gives a compile time error ?

package com.soflow;

import java.util.List;

public abstract class Shape {
}

class Rectangle extends Shape {
    private int x, y, width, height;

    public void addRectangle(List<? extends Shape> shapes) {
        shapes.add(0, new Rectangle()); // compile-time error!
        }
}

What I am failing to understand here is that why is it not allowing me to add a subtype of shapes into the "shapes" list ? And why is it complaining at compile time ? I believe compiler can see that there exists an IS-A relation between Rectangle and Shape. I am confused now. Any help is greatly appreciated.

Thanks, Maneesh Sharma

Any help will be appreciated

Maneesh
  • 119
  • 10
  • http://stackoverflow.com/questions/35098976/compile-time-error-while-using-wildcard-in-list – Viet Jan 31 '16 at 01:43

2 Answers2

3

List<? extends Shape> means a list parametrized with any subclass of Shape, not a list accepting any subclass of shape as its contents. That would just be a List<Shape>.

Imagine that shapes was a List<Triangle> at runtime. This would clearly be an error, since you can't add a Rectangle to a List<Triangle>.

However, let's consider why List<Rectangle>, List<Shape> or List<? super Shape> would be correct here. In the first case, it's clear: A List<Rectangle> would accept instances of Rectangle. In the second, since all Rectangle instances are assignable to Shape, they can be put into a List<Shape>. In the third case, the bound guarantees that the list will accept Shape by being a superclass of Shape.

Remember the following phrase: "producer extends, consumer super". Here the list is a consumer of added items, so it needs to be super.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

Change List<? extends Shape> shapes to List<? super Shape> shapes or List<Shape> shapes.

user2004685
  • 9,548
  • 5
  • 37
  • 54