Is there something wrong with ArrayList nested initialization?

Consider the following classes:

class A{ }
class B extends A{ }

As we know, this compiles fine:

List<? extends A> xx = new ArrayList<B>();
List<? extends List<? extends A>> xy = new ArrayList<List<? extends A>>();

But this gives a compile time error

List<? extends A> yx = new ArrayList<? extends A>();
List<? extends List<? extends A>> yy = new ArrayList<? extends List<? extends A>>();

The error says:

required: class or interface without restrictions

I know that the new values ​​interpreted by the compiler for the above initializations are different and therefore cannot be discarded safely. But what does “borderless” mean in the above error message?

+4
source share
3 answers

This error refers to creating a new ArrayListone for which the direct type of the top-level type uses a wildcard. This is unacceptable even though a nested type parameter is allowed to have a wildcard.

JLS, 15.9, " " , :

TypeArguments new (, , (§4.5.1).

"", , .

, :

[ ] , .. . , . , : , ; , . : , ; , .

( )

, , .

, , . List, ArrayList. List , .

Java ( new), , .

+4

(§15.9):

[ ] new (, , .

. ( new ArrayList<List<?>>), ( new ArrayList<?>).

, , , (§4.5.1):

TypeArguments:
    < TypeArgumentList >

TypeArgumentList:
    TypeArgument {, TypeArgument}

TypeArgument:
    ReferenceType
    Wildcard

Wildcard:
    {Annotation} ? [WildcardBounds]

WildcardBounds:
    extends ReferenceType
    super ReferenceType

, TypeArgument TypeArgumentList, , TypeArgument ReferenceType, a Wildcard. , , , .

+2

/ .

? extends A
? extends List<? exetnds A>

, ( "" ).

B
List<? extends A>

.

new ArrayList<B>();
new ArrayList<List<? extends A>>();

. B, - List, ? extends A.

ArrayList(); ArrayList > ();

undefined. .

, List<? extends A> , . List<? extends List<? extends A>> . , List<? extends A>. ,

new ArrayList<? extends A>();

.

Understood?

0
source

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


All Articles