Java泛型:List< Container<>> =新的链接列表<容器< Double>>()被禁止? [英] Java generics: List<Container<?>> = new LinkedList<Container<Double>>() is prohibited?
问题描述
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< Container<>> =新的链接列表<容器< Double>>()被禁止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!