Java adding to a unknown type generic list

别来无恙 提交于 2019-11-28 09:11:58
Snicolas

You can't add objects in a Collection defined using wildcards generics. This thread might help you.

Indeed you are creating a collection that is, yes, the super type of every collection, and as such, can be assigned to any collection of generics; but it's too generic to allow any kind of add operation as there is no way the compiler can check the type of what you're adding. And that's exactly what generics are meant to : type checking.

I suggest you read the thread and see that it also apply to what you wanna do.

Your collection is just too generic to allow anything to be added in. The problem has nothing to do with the right hand side of the asignment (using a singleton or reflection), it's in the left hand side declaration type using wildcards.

If I get what you mean, you have a class C, which is unknown at compile time, and you want to create an ArrayList<C>, in a type safe way. This is possible:

Class<?> c = ...;
ArrayList<?> al = listOf(c);

static <T> ArrayList<T> listOf(Class<T> clazz)
{
    return new ArrayList<T>();
}

This is the theoretically correct way of doing it. But who cares. We all know about type erasure, and there's no chance Java will drop type erasure and add runtime type for type parameters. So you can just use raw types and cast freely, as long as you know what you are doing.

You could just use ArrayList<Object>, to which you can add() anything.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!