使用两个不同的泛型参数调用泛型函数仍然可以编译

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)

Lou*_*man 7

T被强迫向上Object.该Integer[]可upcasted到Object[],并且String得到upcasted来Object,它typechecks.

  • 除此之外:变量`r`确实是一个原始类型(不是一个对象),但这里涉及自动装箱,所以它工作:). (2认同)