汽车由编译器结合泛型(类型推断) [英] auto binding (type inference) of generic types by the compiler
问题描述
以下code的编译错误,在T3的行:
the following code has compilation error in the line of t3:
public <E> List<E> getList()
{
return new ArrayList<E>();
}
public <T> void first()
{
List<T> ret = new ArrayList<T>();
List<T> list = getList();
T t1 = ret.get(0);
T t2 = list.get(0);
T t3 = getList().get(0);
}
该错误信息是:
类型不匹配:不能从对象转换至T
我知道我可以通过铸造或手工绑定解决这个问题,我的问题是:就这么困难的编译器进行自动绑定,是有它失败的情况下 <? / p>
编辑:添加了错误信息
I know I can fix the problem using casting or manual binding, my questions is: is it so difficult for the compiler to do auto-binding, is there a case that it will fail?
编辑:增加了一个例子,如何不发生错误
added the error message.
编辑:删除了第二个例子,因为这是令人困惑,提出的问题更加清晰
added another example how the error does not occurred.
推荐答案
在第一种情况下,你有一个名为 T
类型参数的两个通用的方法,但这种类型的参数不同的,所以让我们分配不同的名字对他们说:
In the first case you have two generic methods with type parameters named T
, but these type parameters are different, so let's assign different names to them:
然后,它的工作原理如下:
public <E> List<E> getList() { ... }
public <T> void first() { ... }
-
名单,LT的元素; T&GT;
(即类型的对象T
)被分配给类型的变量T
,所以一切正常:
Then it works as follows:
An element of List<T>
(that is object of type T
) is assigned to the variable of type T
, so everything works fine:
首先,类型的对象列表&LT; E&GT;
分配给列表&LT; T&GT;
。这个语句工作得很好,因为类型参数电子
从分配的左侧的类型推断,所以 T
= 电子
。然后,它可以作为在previous情况:
List<T> ret = new ArrayList<T>();
T t1 = ret.get(0);
Firstly, an object of type List<E>
is assigned to List<T>
. This statement works fine since type parameter E
is inferred from the type of the left side of assignment, so T
= E
. Then it works as in the previous case:
在这种情况下,你想指定类型的对象电子
来类型的变量 T
,但电子
无法推断出,因此假定为对象
,所以分配失败:
List<T> list = getList();
T t2 = list.get(0);
In this case you are trying to assign object of type E
to the variable of type T
, but E
cannot be inferred and therefore assumed to be Object
, so assignment fails:
您可以通过电子
绑定到 T
手动修复此问题
You can fix this behaviour by binding E
to T
manually:
T t3 = this.<T>getList().get(0);
在泛型类的情况下 TestGenerics&LT; T&GT;
你没有两个独立的类型参数,所以 T
在这两种方法是指相同类型的
In the case of generic class TestGenerics<T>
you don't have two independent type parameters, so T
in both methods refers to the same type.
这篇关于汽车由编译器结合泛型(类型推断)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!