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

后端 未结 3 1743
滥情空心
滥情空心 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<Animal> animals = new ArrayList<Animal>();
    

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

    On the other hand, you should use List<? extends Animal> 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.

    0 讨论(0)
  • 2020-12-02 03:36

    When you use wildcards with extends, you can't add anything in the collection except null. Also, String is a final class; nothing can extend String.

    Reason: If it were allowed, you could just be adding the wrong type into the collection.

    Example:

    class Animal {
    
    }
    
    class Dog extends Animal {
    
    }
    
    class Cat extends Animal {
    
    }
    

    Now you have List<? extends Animal>

    public static void someMethod(List<? extends Animal> list){
        list.add(new Dog()); //not valid
    }
    

    and you invoke the method like this:

    List<Cat> catList = new ArrayList<Cat>(); 
    someMethod(catList);
    

    If it were allowed to add in the collection when using wildcards with extends, you just added a Dog into a collection which accepts only Cat or subtype type. Thus you can't add anything into the collection which uses wildcards with upper bounds.

    0 讨论(0)
  • 2020-12-02 03:54

    String is a final class and cannot be extended. Additionally, for the case you seem to be interested in, you do not need the extends keyword. List<String> will do what you seem to want. That will allow Strings and sub-classes of String (if such a thing could exist, which it can't since String is final).

    0 讨论(0)
提交回复
热议问题