考虑使用Java Puzzlers中的代码
class Gloam<T>{
String glom(Collection<?> objs ) {
System.out.println("collection");
String result = "";
for (Object o : objs ){
result += o;
}
return result;
}
int glom(List <Integer> ints ) {
System.out.println("List");
int result = 0;
for ( int i : ints )
result += i ;
return result;
}
public static void main(String[] args) {
List<String> strings = Arrays.asList("1", "2", "3");
System.out.println(new Gloam().glom(strings));
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个程序时,它会给出类强制转换异常,但是如果我在main方法中为Gloam类提供任何Generic参数,它可以正常工作.
public static void main(String[] args) {
List<String> strings = Arrays.asList("1", "2", "3");
System.out.println(new Gloam<Date>().glom(strings));
}
Run Code Online (Sandbox Code Playgroud)
我不明白泛型如何在类类型参数中工作?
如果没有传递给构造函数的泛型类型,则会擦除所有类型,并向编译器提供此选项
String glom ( Collection );
int glom ( List );
Run Code Online (Sandbox Code Playgroud)
该类型也从strings定义的变量中删除main,因此其类型为List.
因为List比Collection它选择的更具体int glom ( List ).
现在,如果你已经指定了泛型参数,则没有类型擦除发生,编译器知道它不能匹配int glom ( List<Integer> )到List<String>,所以它回落到String glom ( Collection<?> )
| 归档时间: |
|
| 查看次数: |
2891 次 |
| 最近记录: |