本文介绍了泛型 - 不能使用无界通配符添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实例化以下列表:

I instantiate the following list:

// I am just revising generics again and the following is just cursory code!
List<? super Integer> someList = new ArrayList<Object>();
someList.add(new Object());

以上行不通。我收到一个编译器错误。但是,以下工作:

The above will not work. I get a compiler error. However, the following works:

List<? super Integer> someList = new ArrayList<Object>();
someList.add(11);

我知道您可以将对象添加到包含无界通配符,不是一个有界的通配符。

I am aware that you can add objects to a collection which contains an unbounded wildcard, not a bounded wildcard.

然而,为什么上述不起作用?
一个Object是一个Integer的超类型,为什么我不能添加它?

However, why does the above not work?An Object is a supertype of an Integer, so why can't I add it?

推荐答案

它是一个超类型Integer的列表,并不是列表可以包含任何超类型的Integer。换句话说,对于编译器来说,它可以是 List< Integer> ,a List< Number> List< Object> ,但它不知道哪个,所以你不能在List中添加任何东西。唯一可以安全添加的是Integer,因为它保证了List可以容纳的任何类型的子类型。

That declares that it's a list of something that's a supertype of Integer, not that the list can contain anything that's a supertype of Integer. In other words, to the compiler, it could be a List<Integer>, a List<Number> or a List<Object>, but it doesn't know which, so you can't add just anything to the List. The only thing you can safely add is an Integer, since that's guaranteed to be a subtype of any type the List could potentially hold.

换句话说,代表一个类型,而不是任何类型。这是一个非显而易见但重要的区别。

In other words, the ? represents one type, not any type. It's a non-obvious but important distinction.

这篇关于泛型 - 不能使用无界通配符添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:45