As we konw, we can't add any element except null
into an list like List<? extends Number>
, so why the sentence can be compiled, wait for your answer, thanks!
List<? extends Number> arr = Arrays.asList(1,2,3.1f,4.1d)
As we konw, we can't add any element except null
into an list like List<? extends Number>
, so why the sentence can be compiled, wait for your answer, thanks!
List<? extends Number> arr = Arrays.asList(1,2,3.1f,4.1d)
That code is not "adding" an element to a List<? extends Number>
. Adding an element into a List<? extends Number>
looks something like:
arr.add(1);
which doesn't compile as you'd expect.
What your code is doing is creating a list containing 1, 2, 3.1, and 4.1, using Arrays.asList
. Then you assign that list to the variable arr
. You never add
ed to arr
.
When we say "you can only add null to a list of type List<? extends Number>
", we really only mean that if you have a variable of type List<? extends Number>
(arr
in this case), you can only pass null
to its add
method (or any other method that accepts its generic type parameter).
It does not mean that there is no absolutely no way to add elements to the list object referenced by that variable. You just can't add to it by directly calling the add
method.
For example,
ArrayList<Integer> ints = new ArrayList<>();
ArrayList<? extends Number> numbers = ints; // now numbers and ints refer to the same list
System.out.println(numbers); // prints []
ints.add(1);
System.out.println(numbers); // prints [1]
It seems you are having an import issue here, regarding util.Arrays and util.List. There are functional errors in the code.
import java.util.Arrays;
import java.util.List;
public class Runner {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<? extends Number> arr = Arrays.asList(1,2,3.1f,4.1d);
arr.forEach(e -> {
System.out.println(e);
});
}
}