Home >Java >javaTutorial >Why Can't I Add Data to a `List
Adding Data to List extends Number>
The dilemma faced when attempting to add elements to a List extends Number> stems from the wildcard declaration's constraint. In such a declaration, the variable can hold any value from a family of types. This implies that the following assignments are valid:
List<? extends Number> foo3 = new ArrayList<Number>(); List<? extends Number> foo3 = new ArrayList<Integer>(); List<? extends Number> foo3 = new ArrayList<Double>();
However, this wildcard declaration prohibits direct addition of elements to the list, as the specific type of list is unknown. For instance, adding an Integer to foo3 is not allowed because it could potentially be an ArrayList In contrast, the wildcard declaration List super Number> allows for the addition of Number or its superclasses. Conversely, it restricts the retrieval to the type Number or its subclasses. This behavior emerges from ensuring that elements added to the list will not violate its integrity. To illustrate the practical implications, the following calls to Collections.copy() demonstrate how wildcards enable flexibility in copying data between lists of related types: In conclusion, adding data to List extends Number> is not possible due to the uncertainty about the underlying list's type, while reading from List super Number> is restricted to the type Number and its subclasses. Wildcards provide versatility in copying data between lists of related types, as exemplified by Collections.copy(). The above is the detailed content of Why Can't I Add Data to a `List. For more information, please follow other related articles on the PHP Chinese website!Collections.copy(new ArrayList<Number>(), new ArrayList<Number>());
Collections.copy(new ArrayList<Number>(), new ArrayList<Integer>());
Collections.copy(new ArrayList<Object>(), new ArrayList<Number>());
Collections.copy(new ArrayList<Object>(), new ArrayList<Double>());