【发布时间】:2017-03-11 09:19:47
【问题描述】:
Oracle docs on Java generics type inference 给出了这个例子:
class MyClass<X> {
<T> MyClass(T t) {
// ...
}
}
考虑以下 MyClass 类的实例化:
new MyClass<Integer>("")该语句为正式类型参数
X显式指定类型Integer。编译器为形式类型参数T推断类型String,因为此构造函数的实际参数是一个String 对象。
我尝试过这个。我定义了以下类:
class Box<T,S>
{
T item;
S otherItem;
<X> Box(S p1, X p2)
{
otherItem = p1;
}
public static void main(String[] args)
{
/* Below gives compile time error:
The constructor Box<String,Integer>(String, int) is undefined
*/
Box box4 = new Box<String,Integer>("Mahesh",11);
}
}
以上对构造函数的调用给了我编译时错误:
The constructor Box<String,Integer>(String, int) is undefined
我知道我可以通过指定菱形来做到这一点:
Box box4 = new Box<>("Mahesh",11);
但只是好奇,我该如何通过明确指定type witness来做到这一点...
【问题讨论】: