0

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?

2
  • Is it a typo that you have both SomeType and Type in your question? Commented Apr 30, 2014 at 8:27
  • no i've the correct type in my code. Commented Apr 30, 2014 at 8:28

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

so wherever we mention T, eg: List<T> it means that it returns a list of <T extends Type> ?
Exactly. But T is always the same over whole the way.
but when i'm calling function everytime i need to pass class<T> also anyway to eliminate that? just like calling <Type>method()?
You do not need it for method addItem. You probably need it for getAllItems but since you have not shared code of this method I cannot say whether you can eliminate this parameter. Try to ask another question and share more code.
0

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);

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.