Add Strings through use of generic 'extends' causes compiler error

后端 未结 3 1768
滥情空心
滥情空心 2020-12-02 03:20

Below code :

List genericNames = new ArrayList();
genericNames.add(\"John\");

Gives compiler error :

3条回答
  •  无人及你
    2020-12-02 03:30

    Just want to add to the answer of GanGnaMStYleOverFlow that you can add an object of any subtype of Animal to the following list:

    List animals = new ArrayList();
    

    You should use such list whenever you think that it can contain any kind of animals.

    On the other hand, you should use List when you want to specify that the list contains some kind of animal but you don't know which one. Since you don't know what kind of animals are there, you cannot add any.

提交回复
热议问题