开发者

Java Collection<Object> or Collection<?>

开发者 https://www.devze.com 2023-03-25 05:40 出处:网络
I try use List instead of List List<?> list = new ArrayList<Integer>(); ... list.add(1); //compile error

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

精彩评论

暂无评论...
验证码 换一张
取 消