首页 > 代码库 > 泛型数组

泛型数组

1.直接使用T

public class GenericArray<T> {    private T[] array;        public GenericArray(int size){        array = (T[]) new Object[size];    }        public void put(int index, T item){        array[index] = item;    }        public T get(int index){        return array[index];    }        public T[] rep(){        return array;    }        public static void main(String[] args) {        GenericArray<Integer> gai = new GenericArray<Integer>(10);        //Integer[] ia = gai.rep();//运行时是Object类型, java.lang.ClassCastException        Object[] oa = gai.rep();     }}

 

2.在内部使用Object,取出时转为T。ArrayList就是这种实现

public class GenericArray1<T> {    private Object[] array;        public GenericArray1(int size){        array = (T[]) new Object[size];    }        public void put(int index, T item){        array[index] = item;    }        public T get(int index){        return (T) array[index];    }        public T[] rep(){        return (T[]) array;    }        public static void main(String[] args) {        GenericArray1<Integer> gai = new GenericArray1<Integer>(10);        //Integer[] ia = gai.rep();//运行时是Object类型, java.lang.ClassCastException        Object[] oa = gai.rep();     }}

 

3.使用类型标记

 1 public class GenericArrayWithTypeToken<T> { 2     private T[] array; 3      4     public GenericArrayWithTypeToken(Class<T> type ,int size){ 5         array = (T[]) Array.newInstance(type, size); 6     } 7      8     public void put(int index, T item){ 9         array[index] = item;10     }11     12     public T get(int index){13         return array[index];14     }15     16     public T[] rep(){17         return  array;18     }19     20 21     22     public static void main(String[] args) {23         GenericArrayWithTypeToken<Integer> gai = new GenericArrayWithTypeToken<Integer>(Integer.class,10);24         Integer[] ia = gai.rep(); 25 26     }27 }