Home >Java >javaTutorial >Why Can't I Add Data to a `List

Why Can't I Add Data to a `List

Patricia Arquette
Patricia ArquetteOriginal
2025-01-03 10:46:39214browse

Why Can't I Add Data to a `List

Adding Data to List

The dilemma faced when attempting to add elements to a List 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&gt(); 

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 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:

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>());

In conclusion, adding data to List is not possible due to the uncertainty about the underlying list's type, while reading from List 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn