Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I have a List which is declared like this :

 List<? extends Number> foo3 = new ArrayList<Integer>();

I tried to add 3 to foo3. However I get an error message like this:

The method add(capture#1-of ? extends Number) in the type List<capture#1-of ?

extends Number> is not applicable for the arguments (ExtendsNumber)

1 Answer

0 votes
by (46k points)
You can't (without unsafe casts). You can only read from them.

The problem is that you don't know what exactly the list is a list of. It could be a list of any subclass of Number, so when you try to put an element into it, you don't know that the element actually fits into the list.

For example the List might be a list of Bytes, so it would be an error to put a Float into it.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...