Can I use the generics template in a list declaration?

Consider the following codes:

class Super {}
class Sub extends Super {}
class Test {
    public static void main(String[] args) {
        List<? extends Super> list = new ArrayList<Sub>(); //1
        list.add(new Sub()); //2
    }
}

Line 1 compiles successfully, but line 2 does not compile:

The method add(capture#2-of ? extends Super) in the type List<capture#2-of ? extends Super> is not applicable for the arguments (Sub)

My questions are:
1) Why is line 1 compiling successfully?
2) Is line 1 good practice when declaring a list (or other collections)?
3) Why does line 2 fail to compile after the list has been declared as type Sub in line 1?
4) Autocomplete Eclipse says that now only "null" items are allowed in the list. What for?

Thanks a lot!

+4
source share
5 answers

1) Why is line 1 compiling successfully?

, List<Sub> List<? extends Super>, true, List .

? , , List<Sub> List<Sub1>, , .

2) 1 ( )?

, List<Sub>, , , List , Utilities.

3) 2 , Sub 1?

, , , .

4) Eclipse , "" . ?

null , null.

PECS ( )

:

+4

, 1, . . Collection.addAll(Collection<? extends E>). Super, List<Super>.

+3

list , Super. , Sub , . , .

<? extends Super> , Super. , .

+2

1) 1 ?

, , ( ) Super, , Super.

Sub Super, , Sub, , Super, List<? extends Super> list = new ArrayList<Sub>();, .

2) 1 ( )?

, , . ( / ), , .

, . Collection<Number>, Collection<Integer> . Collection<? extends Number>, Collection<Integer>.

3) 2 , Sub 1?

, . Super Sub?

List<? extends Number> list. , List<Number>, a List<Double> List<Integer> , , , list.add( new Integer(1) ); . .

4) Eclipse , "" . ?

, null , , , null .

+1

1) 1 ?

list " , Super". Sub. Sub - ", Super".

2) 1 ( )?

. . generics, , , .

3) 2 , Sub 1?

. , list "-, Super", Sub, . Sub , "-" - , Sub; Sub2, :

class Super {}
class Sub extends Super {}
class Sub2 extends Super {}
Sub2 s = new Sub();

, , , , - . . , .

4) Eclipse , "" . ?

null - the only value that any possible reference type has and therefore is compatible with this list, regardless of what the wildcard means.

+1
source

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


All Articles