Home > Java > javaTutorial > How Can I Add Data to a List

How Can I Add Data to a List

Linda Hamilton
Release: 2024-12-15 07:48:11
Original
863 people have browsed it

How Can I Add Data to a List

How Can You Add Data to Structures of the Type List

While working with a list defined as List foo3 = new ArrayList

The method add(capture#1-of ? extends Number) in the type List is not applicable for the arguments (ExtendsNumber)

This error stems from the wildcard declaration of List foo3. It indicates that foo3 can hold values from a range of types that inherit from Number. This includes Number, Integer, and Double. Given this flexibility, it becomes difficult to determine what type of object can be safely added to foo3.

For instance:

  • You cannot add an Integer because foo3 could be referencing a List.
  • You cannot add a Double because foo3 could be referencing a List.
  • You cannot add a Number because foo3 could be referencing a List.

Ultimately, you cannot add anything to List because there is no way to guarantee the type of the underlying list. The only certainty is that you can read from it and obtain a value of type T or a subclass of T.

On the other hand, the reverse logic applies to ? super. For example, List foo3 = new ArrayList since you cannot guarantee the actual type of the underlying list. The only "guarantee" is that you can add values of type T (or any subclass of T) without compromising the integrity of the list.

The above is the detailed content of How Can I Add Data to a List. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template