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 a开发者_开发知识库nd 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>();
精彩评论