Sta*_*tan 4 java generics compiler-errors compilation
以下代码甚至可以编译怎么可能?据我所知,count函数是用两种不同的类型调用的,但编译器没有抱怨并且很乐意编译这段代码.
public class Test {
public static <T> int count(T[] x,T y){
int count = 0;
for(int i=0; i < x.length; i++){
if(x[i] == y) count ++;
}
return count;
}
public static void main(String[] args) {
Integer [] data = {1,2,3,1,4};
String value = "1";
int r =count(data,value);
System.out.println( r + " - " + value);
}
}
Run Code Online (Sandbox Code Playgroud)
T被强迫向上Object.该Integer[]可upcasted到Object[],并且String得到upcasted来Object,它typechecks.
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |