【发布时间】:2018-04-25 02:01:51
【问题描述】:
考虑以下示例:
public class Learn {
public static <T> T test (T a, T b) {
System.out.println(a.getClass().getSimpleName());
System.out.println(b.getClass().getSimpleName());
b = a;
return a;
}
public static void main (String[] args) {
test("", new ArrayList<Integer>());
}
}
在main 方法中,我使用String 和ArrayList <Integer> 对象调用test。两者是不同的东西,将ArrayList 分配给String(通常)会产生编译错误。
String aString = new ArrayList <Integer> (); // won't compile
但我在test 的第 3 行正是这样做的,程序编译并运行良好。首先我认为类型参数T 被替换为与String 和ArrayList 兼容的类型(如Serializable)。但是test 中的两个println 语句将“String”和“ArrayList”分别打印为a 和b 的类型。我的问题是,如果 ais String 和 b 在运行时是 ArrayList,我们如何将 a 分配给 b。
【问题讨论】:
-
提示:您将
a和b的静态类型与它们的动态类型混淆了。