正常情况下,泛型数组是无法初始化的,比方这样T [] a=new T[5] ,就会报错;
但是通过反射可以实现泛型数组。代码如下:
/** * Created by wangbin10 on 2019/1/2. * 在泛型方法中返回泛型数组 */ public class Test { public static void main(String[] args) { Integer[] x = {1, 3, 5, 7}; Integer[] y = {2, 4, 6, 8}; Integer[] merge = merge(x, y); System.out.println(Arrays.toString(merge)); } public static <T> T[] merge(T [] x,T[] y) { int z=x.length+y.length; T[] ts = (T[]) Array.newInstance(x.getClass().getComponentType(), z); for (int i = 0; i < x.length; i++) { ts[i]=x[i]; } for(int j=0;j<y.length;j++) { ts[j+y.length]=y[j]; } return ts; } }