Dineshkumar
Dineshkumar

Reputation: 4245

How to add element in ArrayList<? extends SomeType> via a method

i want to add element extending Type to ArrayList.

ArrayList<? extends Type> 

i defined a method as below

public <T extends Type> void addItem(T itemToAdd, Class<?> classType) {
    ArrayList<? extends Type> allItems = getAllItems(classType);
    allItems.add(itemToAdd);
}

T itemToAdd is error. because i can't add someother type. i thought but i don't know to mention it and its error!

How to add the item via a method call?

Upvotes: 0

Views: 156

Answers (3)

songyuanyao
songyuanyao

Reputation: 172924

I'm not sure about your declaration of the return value of getAllItems, but you can't put itemToAdd with type T extends Type into ArrayList<? extends Type>. The type of element may be unmatch (different type although both are the derived class of Type), so the ArrayList should be declared as

ArrayList<? super Type> allItems;

which can guarantee itmeToAdd can be put into the ArrayList, or just:

ArrayList<Type> allItems;

Upvotes: 0

FrancoisT
FrancoisT

Reputation: 31

If you define for your List all object must have the same type

If you want to insert multiple class defined simple List and you can insert objects extends Type

Example :

List<Type> list = gellAllItems(class);
list.add(T);

Upvotes: 0

AlexR
AlexR

Reputation: 115338

Think about your definition: ArrayList<? extends Type>. It means list of elements each of them extends Type. It does not mean that each of them is of type T as itemToAdd. To make this code to compile you have to ensure this fact, i.e. use T in all relevant places:

public <T extends Type> void addItem(T itemToAdd, Class<T> classType) {
    List<T> allItems = getAllItems(classType);
    allItems.add(itemToAdd);
}

It probably means that you should change definition of getAllItem() to

public <T extends Type> List<T> getAllItems(Class<T> classType)

BTW please pay attention that I changed your ArrayList to List. Although it is out of the topic but avoid using concrete classes at the left part of assignment operator, as a return value of method and as a method parameter.

Upvotes: 2

Related Questions