首页 > java函数返回一个泛型,会自动转型吗?

java函数返回一个泛型,会自动转型吗?

public class GenericsDemo30{  
    public static void main(String args[]){  
        Integer i[] = fun1(1,2,3,4,5,6) ;   // 返回泛型数组  
        fun2(i) ;  
    }  
    public static <T> T[] fun1(T...arg){  // 接收可变参数  
        return arg ;            // 返回泛型数组  
    }  
    public static <T> void fun2(T param[]){   // 输出  
        System.out.print("接收泛型数组:") ;  
        for(T t:param){  
            System.out.print(t + "、") ;  
        }  
    }  
}; 

疑问1:func1 自动将返回的T转型为了 Integer了?

public static <T> T $(Activity activity, int resid) {
        return (T) activity.findViewById(resid);
 }

public static <T> T $(View view, int resid) {
    return (T) view.findViewById(resid);
}

使用的时候,直接

T怎么就知道是TextView的


这有什么奇怪么?

public static <T> T[] fun1(T...arg) 已经定义了参数类型是 T 的嘛,你传入的参数是 int,会自动转成 Integer,所以这个时候 fun1 相当于是下面这个

javapublic static Integer[] fun1(Integer...arg)
【热门文章】
【热门文章】