Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collection<Object> or Collection<?>

Tags:

java

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?

like image 748
Akvel Avatar asked Aug 05 '11 03:08

Akvel


2 Answers

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>.

like image 99
Paŭlo Ebermann Avatar answered Nov 10 '22 07:11

Paŭlo Ebermann


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

The generic type always has to be the same.

like image 45
Oscar Gomez Avatar answered Nov 10 '22 06:11

Oscar Gomez