Zeemee
Zeemee

Reputation: 10704

Why can't I add SuperType to List<T> where <T extends SuperType>?

With

public class SuperType {
}

and

public class TestClass<T extends SuperType > {

    public void doSomething() {
        List<T> list = new ArrayList<T>();
        list.add(new SuperType ()); // ERROR
    }
}

it won't compile, giving me

The method add(T) in the type List is not applicable for the arguments (SuperType)

But why?

Upvotes: 2

Views: 535

Answers (4)

Reimeus
Reimeus

Reputation: 159754

The type is only meant for sub classes of SuperType but not the SuperType itself. Instead use

List<SuperType> list = new ArrayList<SuperType>();
list.add(new SuperType ()); 

Upvotes: 4

saurav
saurav

Reputation: 3462

Type only used to express what all type it can be , in your case it can be of anytype that is a subclass of SuperType and Supertype itself.

Thanks

Upvotes: 0

zapl
zapl

Reputation: 63955

Assume you have

public class SuperType {
}

public class SubType extends SuperType {
}

and use TestClass<SubType> your code becomes

public class TestClass<SubType> {

    public void doSomething() {
        List<SubType> list = new ArrayList<SubType>();
        list.add(new SuperType ());
    }
}

That has to error because a new SuperType() is not specific enough. It has to be at least a SubType.

Upvotes: 7

Saj
Saj

Reputation: 18702

You should have got something in line of-

SuperType cannot be converted to T by method invocation conversion

Meaning using type declaration in implementation is not valid.

When you say-

T extends SuperType

You are actually saying that the parameter can be a SuperType or any subtype of your SuperType.

Should be-

List<SuperType> list = new ArrayList<SuperType>();

Upvotes: 4

Related Questions