Java Collection <Object> or Collection <?>

I am trying to use List instead of List

 List<?> list = new ArrayList<Integer>(); ... list.add(1); //compile error 

What am I doing wrong and how does the new value differ from Integer? Maybe I'm using List in my project?

+6
source share
4 answers

List<?> Means a list of some type, but we donโ€™t know which type. You can put objects of the desired type on the list, but since you do not know the type, you really cannot put anything on such a list (other than null ).

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

+10
source
 List<Integer> list = new ArrayList<Integer>(); 

The general type must always be the same.

+4
source
 List<Integer> list = new ArrayList<Integer>(); ... list.add(1); 
+1
source
 List<?> list = new ArrayList<Integer>(); 

? means some type, you must specify the type as a whole. therefore the correct syntax is:

 List<Integer> list = new ArrayList<Integer>(); 
+1
source

Source: https://habr.com/ru/post/894345/


All Articles