为什么通用列表的声明有所不同? [英] Why is the difference in declaration of generic Lists?
问题描述
我想删除两个列表:
第一个是整数列表。我把它分解为:
I want to decare two Lists: First is a list of Integers. I decare it as:
List<Integer> ints= Arrays.asList(1,2,3);
效果很好。
对象列表。我声明为:
List<Object> objs= Arrays.asList(1,2.13,"three");
但是在eclipse中写错了。错误是:
But it gives a error in eclipse as soon as I write it. The error is:
Multiple markers at this line
- Type mismatch: cannot convert from List<Object&Comparable<?>&Serializable> to
List<Object>
- Type safety: A generic array of Object&Comparable<?>&Serializable is created for
a varargs parameter
而是如果我写
List<Object> objs = Arrays.<Object>asList(1,2.13,"three");
效果很好。
无法找出原因。
推荐答案
15.12.2.7基于实际参数引用类型参数 b
$ b
15.12.2.7 Inferring Type Arguments Based on Actual Arguments
超类型约束T:> X意味着该解是X的
超类型之一。给定T上的这些约束,我们可以将
每个约束暗示的超类的集合,因为
类型参数必须是所有约束的成员。然后我们可以选择在交集中的
最具体的类型
A supertype constraint T :> X implies that the solution is one of supertypes of X. Given several such constraints on T, we can intersect the sets of supertypes implied by each of the constraints, since the type parameter must be a member of all of them. We can then choose the most specific type that is in the intersection
String
, Double
和 Integer
可比较和可序列化
。所以当你写
The most restrictive type intersection between String
,Double
and Integer
is both the interfaces Comparable
and Serializable
. So when you write
Arrays.asList(1,2.13,"three");
它推断 T
为 implements Comparable<?>,Serializable
。然后就好像你在做
It infers T
to be implements Comparable<?>, Serializable
.Then it is as if you are doing
List<Object> objs = new List<T extends Comparable<?>, Serializable>
很明显,这是不允许的。
另一方面,使用
Obviously, this is not allowed.
On the other hand, when you specify Object
explicitly using
Arrays.<Object>asList(1,2.13,"three");
无推理
这篇关于为什么通用列表的声明有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!