看看这个简单的 Java 泛型示例:
class List<T> {
T head;
List<T> next;
}
class A<T> {
List<T> l;
public <T> int length() {
List<T> l = this.l;
int c = 1;
while (l.next != null) {
c++;
l = l.next;
}
return c;
}
public static void main(String[] args) {
A<Integer> a = new A<Integer>();
a.l = new List<Integer>();
a.l.head = 123;
a.l.next = new List<Integer>();
a.l.next.head = 432;
System.out.println("list length: " + a.length());
}
}
它编译时出错,声称类型不兼容,但声称这两个变量是同一类型:
$ javac A.java && java A
A.java:10: incompatible types
found : List<T>
required: List<T>
List<T> l = this.l;
^
1 error
如果我将 length() 的第一行更改为List<T> l = (List<T>)(Object)this.l;
,它可以工作。为什么?