如何将整数元素添加到泛型通配符的 ArrayList 中?

编程入门 行业动态 更新时间:2024-10-27 02:22:00
本文介绍了如何将整数元素添加到泛型通配符的 ArrayList 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个 ArrayList 通用通配符类型,它将 Number 作为扩展.我正在尝试将整数值添加到 ArrayList.

但是它给了我一个错误说

ArrayList<?扩展数>numberList = new ArrayList();numberList = new ArrayList();numberList.add(100);

<块引用>

ArrayList 类型中的 add(int, capture#2-of ?) 方法不适用于参数 (int).

我也尝试过这种方式,但给了我同样的错误

ArrayList<?>numberList = new ArrayList();numberList = new ArrayList();numberList.add(100);

错误是:

<块引用>

ArrayList 类型中的 add(int, capture#2-of ?) 方法不适用于参数 (int)

解决方案

你不能.<代码>?extends 部分基本上告诉编译器:它是某种类型,我不知道,但它扩展了 Number.

所以编译器不能保证你要添加的任何类型与未知类型兼容.因此,您无法向此类集合添加任何内容.

I have a ArrayList generic wildcards type, which is taking Number as extends. I am trying to add the integer values to the ArrayList.

Buts it's giving me an error saying that

ArrayList<? extends Number> numberList = new ArrayList<Number>();
    numberList = new ArrayList<Integer>();
    numberList.add(100);

The method add(int, capture#2-of ?) in the type ArrayList<capture#2-of ?> is not applicable for the arguments (int).

I have tried with this way also, but is giving me the same error

ArrayList<?> numberList = new ArrayList<Number>();
    numberList = new ArrayList<Integer>();
    numberList.add(100);

The error is :

The method add(int, capture#2-of ?) in the type ArrayList<capture#2-of ?> is not applicable for the arguments (int)

解决方案

You can't. the ? extends part basically tells the compiler: it is of some type, which I don't know, but which extends Number.

So the compiler can't guarantee that the type of whatever you want to add is compatible to the unknown type. Therefor you can't add anything to such a collection.

这篇关于如何将整数元素添加到泛型通配符的 ArrayList 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:34:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884902.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通配符   整数   如何将   元素   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!