Tom*_*ski 19 java generics polymorphism parametric-polymorphism
我在我的大学开设了高级编程课程,我对理解这段代码的工作方式有点麻烦.
public final class GenericClass<T> {
private void overloadedMethod(Collection<?> o) {
System.out.println("Collection<?>");
}
private void overloadedMethod(List<Number> o) {
System.out.println("List<Number>");
}
private void overloadedMethod(ArrayList<Integer> o) {
System.out.println("ArrayList<Integer>");
}
public void method(List<T> l) {
overloadedMethod(l);
}
public static void main(String[] args) {
GenericClass<Integer> test = new GenericClass<Integer>();
test.method(new ArrayList<Integer>());
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这段代码会打印"Collection <?>"?
gog*_*ome 14
声明method(List<T> l)没有指定类型T的任何边界.不能保证T是Number或Number的子类.因此,编译器只能决定此方法调用overloadedMethod(Collection<?> o).
请记住:编译后,类文件中不再提供有关泛型的信息.