Why can't I pass an object of type T to a method on an object of type <? extends T>?

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2010-06-13T20:29:52Z Indexed on 2010/06/13 20:32 UTC
Read the original article Hit count: 143

Filed under:
|

In Java, assume I have the following class Container that contains a list of class Items:

public class Container<T>
{
    private List<Item<? extends T>> items;

    private T value;

    public Container(T value)
    {
        this.value = value;
    }

    public void addItem(Item item)
    {
        items.add(item);
    }

    public void doActions()
    {
        for (Item item : items)
        {
            item.doAction(value);
        }
    }
}

public abstract class Item<T>
{
    public abstract void doAction(T item);
}

Eclipse gives the error: The method doAction(capture#1-of ? extends T) in the type Item is not applicable for the arguments (T)

I've been reading generics examples and various postings around, but I still can't figure out why this isn't allowed. Eclipse also doesn't give any helpful tips in its proposed fix, either. The variable value is of type T, why wouldn't it be applicable for ? extends T?.

© Stack Overflow or respective owner

Related posts about java

Related posts about generics