运行main的结果是:
"Collection<?>".
Run Code Online (Sandbox Code Playgroud)
为什么不用ArrayList<Integer>参数调用方法?
import java.util.*;
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>();
ArrayList l = new ArrayList<Integer>();
test.method(l);
}
}
Run Code Online (Sandbox Code Playgroud)
由于l是a List,唯一匹配的功能是第一个.重载分辨率在编译时完成,而不是在运行时完成.l不考虑其值,仅考虑其类型.
就语言而言,这可能也是:
List l = foo();
test.method(1);
Run Code Online (Sandbox Code Playgroud)
它并不关心什么价值l.
| 归档时间: |
|
| 查看次数: |
633 次 |
| 最近记录: |