Creating Generics Instances: New ArrayList <?> () Vs new ArrayList <List <? >> ()

Why is this allowed:

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

but not that?

List<?> list = new ArrayList<?>(); //Compile error: "Cannot instantiate the type ArrayList<?>"
+4
source share
3 answers

When you create an ArrayList, you need to determine the type of objects it will contain:

  • in the first example, you create an ArrayList that will contain lists of unknown generic types, but they will all be lists.
  • in the second example, you are trying to create an ArrayList of an unknown type that is not allowed.
+3
source

You cannot create an instance of an object with an unknown common, so the second line does not work.

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

, "", , , .

, , , , , . , .

+1

  • - .
  • .

:

CharSequence val = new String("foo");

. val (2), , , CharSequence. (1) , , String. , - new [? extends CharSequence], , .

, . .

new ArrayList<List<?>>()

(2) , T ArrayList<T>. ? Java . , T = ?, T = List<?> , Java.

(1),

List<?> list

, . .

0

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


All Articles