如何将整数元素添加到泛型中通配符的ArrayList? [英] How to add an integer element to ArrayList of wildcards in Generics?

查看:327
本文介绍了如何将整数元素添加到泛型中通配符的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



但是它给了我一个错误,指出

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




方法add(int,capture#2-of?)in类型 ArrayList< capture#2-of?> 不适用于参数(int)。

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

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

错误是:


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


解决方案

你不能。 ?扩展部分基本上告诉编译器:它是某种类型,我不知道,但它扩展了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆