当前位置: 动力学知识库 > 问答 > 编程问答 >

Java Collection<Object> or Collection<?>

问题描述:

I try use List instead of List

List<?> list = new ArrayList<Integer>();

...

list.add(1); //compile error

What i do wrong and how cast new value to Integer?

Maybe i shoud use List in my project?

网友答案:

List<?> means a list of some type, but we don't know which type. You can only put objects of the right type into a list - but since you don't know the type, you in effect can't put anything in such a list (other than null).

There is no way around this, other than declaring your variable as List<Integer>.

网友答案:
List<Integer> list = new ArrayList<Integer>();

The generic type always has to be the same.

网友答案:
List<Integer> list = new ArrayList<Integer>();
...
list.add(1);
网友答案:
List<?> list = new ArrayList<Integer>();

? means some type, you have to specify the Type as Integer. so the correct syntax would be :

List<Integer> list = new ArrayList<Integer>();
分享给朋友:
您可能感兴趣的文章:
随机阅读: