I know adding element to an upper bounded wildacardd list is not allowed as below:
List<? extends Number> list = new ArrayList<>();
list.add(1); // compile time error
The reason is that the list can be either a list of Integer or list of Double.
Just like the explanation in this SO.
But I don't see any type safety issue if we allow adding Number
type to the list.
As we can only do operation to the elements in the list as Number, such as reading from the list Number item = list.get(0);
Can anyone give a concrete example why adding Number element cause type safety issue? Or just java doesn't allow it, but it is possible?
Edit:
There is a SO post talking about PECS saying that You actually cannot add anything (except null) to a Collection<? extends Thing>, because you cannot know at runtime which specific subtype of Thing the collection holds.
But this does not clear my doubt because even we don't know the running type, this doesn't mean there will be safety issue, as long as the generic argument is passed by value. So is it passing by reference in JAVA the main reason we cannot add item to upper-bounded wildcard?