The error:
The method add(capture#1-of ?) in the type List<capture#1-of ?> is not
applicable for the arguments (String)
Code:
List<?> to = new ArrayList<Object>();
to.add(new String("here"));
Since List<?>
is a generic type List and therefore can be of any type, then why it is not accepting String in add method?
A List<?>
is a list of some type, which is unknown. So you can't add anything to it except null without breaking the type-safety of the list:
List<Integer> intList = new ArrayList<>();
List<?> unknownTypeList = intList;
unknownTypeList.add("hello"); // doesn't compile, now you should see why
should a String not be acceptable ?
No. <?>
means the type is unknown and the compiler cannot be sure that any type is acceptable to add (this include String)
You can specify a lower bound:
List<? super Object> to = new ArrayList<Object>();
to.add(new String("here")); // This compiles
Now the compiler is sure that the list can contain any Object
According to wildcards, the question mark (?), called the wildcard, represents an unknown type
and not a generic type, since its an unknown
type the compiler cannot accept String
in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With