Java泛型:List< Container<>> =新的链接列表<容器< Double>>()被禁止? [英] Java generics: List<Container<?>> = new LinkedList<Container<Double>>() is prohibited?

查看:94
本文介绍了Java泛型:List< Container<>> =新的链接列表<容器< Double>>()被禁止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list = new LinkedList< Double>();

但不是

 列表与LT;集装箱<?>> list = new LinkedList< Container< Double>>(); 

其中Container就是类似于

  public class Container< T> {...} 

这是因为我有一个接受 List< Container<>> ,我想用Arrays.asList来传递参数:

  process(Arrays.asList(new Container< Double>(),new Container< Double>())); 

但是语言不允许这样做,因为它推断出 Arrays.asList List< Container< Double>> ,并且不可分配给 List< Container<如果我将一个字符串参数化的容器添加到调用中,那么


$ b
$ b>

(新容器< Double>(),新容器< String>())); $ b

  process(Arrays.asList 

它仍然不起作用,因为它推断出类型 List< Container< ;?扩展了Serializable& Comparable<>>>< / code>为Arrays.asList。只有当我传入一个既不是Comparable也不是Serializable的东西时才能正常工作。



当然,我可以放入一个表达式让编译器闭嘴,但我想知道是否我在这里做错了什么。

解决方案

每个参数化必须通配符:

 列表< ;?扩展Container<>>> list = new LinkedList< Container< Double>>(); 

编辑:我正在通过 Angelika Langer的常见问题解答,但没有找到一个(它可能在那里,但隐藏在500页的某个地方)。



考虑这一点的方法是每个参数都是独立的,编译器不会推断关于参数化的信息,除非您明确地声明这么做。


How come, in Java, I can write

List<?> list = new LinkedList<Double>();

but not

List<Container<?>> list = new LinkedList<Container<Double>>();

where Container is just something like

public class Container<T> { ... }

This came up because I have a method that accepts a List<Container<?>>, and I would like to use Arrays.asList to pass arguments to it:

process(Arrays.asList(new Container<Double>(), new Container<Double>()));

But the language doesn't allow this, because it infers the type of Arrays.asList to be List<Container<Double>>, and that is not assignable to List<Container<?>>.

If I add a String-parameterized Container to the call,

process(Arrays.asList(new Container<Double>(), new Container<String>()));

it still doesn't work, because it infers the type List<Container<? extends Serializable & Comparable<?>>> for Arrays.asList. Only if I pass in something that is neither Comparable nor Serializable does it work properly.

Of course, I can put in a cast and get the compiler to shut up, but I'm wondering if I'm doing something wrong here.

解决方案

Each parameterization must be wildcarded:

List<? extends Container<?>> list = new LinkedList<Container<Double>>();

Edit: I was searching through Angelika Langer's FAQ for an explanation, but didn't find one (it's probably there, but hiding somewhere in the 500 pages).

The way to think about this is that each parameterization is independent, and the compiler will not infer information about the parameterization unless you explicitly say to do so.

这篇关于Java泛型:List&lt; Container&lt;&gt;&gt; =新的链接列表&lt;容器&lt; Double&gt;&gt;()被禁止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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