标签:string 返回值 log put turn lis code arraylist return
public class ArrayOfGeneric{ static Generic<Integer>[] gia; @SupperssWarnings("unchecked") public static void main(String[] args){ gia = (Generic<Integer>[])new Generic[100]; // 通过类型转换匿名对象 //! gia[0] = new Object(); //编译不通过,不能(直接)创建泛型数组实例 } }
public class GenericArray<T> { private T[] array; @SupperessWarning("unchecked") public GenericArray(int sz) { array = (T[]) new Object[sz]; } 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(); //ClassCastException Object[] oa = gai.rep(); //只能返回对象数组类型为Object[]
public class GenericArray2<T> { private Object[] array; //维护Object[]类型数组 @SupperessWarning("unchecked") public GenericArray2(int sz) { array = new Object[sz]; } 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; } //运行时无论怎样都是Object[]类型 public static void main (String[] args){ GenericArray<Integer> gai = new GenericArray<Integer>(10); // Integer[] ia = gai.rep(); //依旧ClassCastException Object[] oa = gai.rep(); //只能返回对象数组类型为Object[] gai.put(0,11); System.out.println(gai.get(0)); // 11 ,出口成功转型 } }
import java.lang.reflect.*; public class GenericArrayWithTypeToken<T> { private T[] array; @SuppressWarning("unchecked") public GenericArrayWithTypeToken(Class<T> type, int sz) { array = (T[]) Array.newInstance(type, sz);//通过反射在运行时构出实际类型为type[]的对象数组,避免了类型擦除,从而转换成功,无ClassCastException } 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) { GenericArrayWithTypeToken<Integer> gawtt = new GenericArrayWithTypeToken<>(Integer.class, 10); Integer[] ia = gawtt.rep(); //能成功返回了! } }
标签:string 返回值 log put turn lis code arraylist return
原文地址:http://www.cnblogs.com/ilinuxer/p/7147941.html