ADOGCATFISH3333 ADOGCATFISH3333 - 4 months ago 9x
Java Question

Java generics - How to add non generic to a generic list

I'm attempting to create a method that will add elements from a defined list, into a generic list.

Here is the code:

private List<IEntity> entities = new ArrayList<IEntity>();

public <T extends IEntity> List<T> values(Class<T> type) {
List<T> types = new ArrayList<T>();

for (IEntity v : entities) {
types.add(v); //Error

return types;

The sytax error occurs on
with the error message
(T) in List cannot be applied to (com.test.entities.IEntity)

Is there any way to do what I'm trying to do efficiently without having to cast?


The compiler is giving you a type error because your program is not safe.

You have a List<T>. You don't know what T is, just that it extends IEntity. (Let's use Number as an example instead of IEntity, to make it more clear.) So you have a List of some kind of Number, maybe its a List, or maybe a List, you don't know. And you're trying to add a Number to it. But you have no reason to believe that this list can hold Number! A List<Integer> cannot hold an arbitrary Number, because you can't put Long or Float or Short into a List<Integer> -- Java generics are invariant.

So, basically your program is broken and the compiler is telling you so.