Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

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

Below code :

List<? extends String> genericNames = new ArrayList<String>();
genericNames.add("John");

Gives compiler error :

Multiple markers at this line - The method add(capture#1-of ? extends String) in the type List is not applicable for the arguments (String) - The method add(capture#1-of ?) in the type List is not applicable for the arguments (String)

What is causing this error ? Should I not be able to add Strings or its subtype since I am extending String within the type parameter ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...