Java中泛型创建数组的总结
在java中,不能通过直接通过T[] tarr=new T[10]的方式来创建数组,最简单的方式便是通过Array.newInstance(Class<t>type,int size)的方式来创建数组例如下面的程序
- public class ArrayMaker<T> {
- private Class<T> type;
-
- public ArrayMaker(Class<T> type) {
- this.type = type;
- }
-
- @SuppressWarnings("unchecked")
- T[] createArray(int size) {
- return (T[]) Array.newInstance(type, size);
- }
-
- List<T> createList() {
- return new ArrayList<T>();
- }
-
-
-
-
- public static void main(String[] args) {
-
-
-
-
-
-
- ArrayMaker<Type> am2 = new ArrayMaker<Type>(Type.class);
- System.out.println(Arrays.asList(am2.createArray(10)));
- System.out.println(Arrays.asList(am2.createList()));
- }
-
- }
-
- class Type {
- @Override
- public String toString() {
- return "type";
- }
- }
|
上面的这个例子比较简单,但是如果你有接触过泛型数组,你便对他的复杂度有一定的了解,由于创建泛型数组比较复杂,所以在实际的应用过程中一般会选择List的对泛型进行存储,如果实在需要使用泛型数组,则需要注意数组的在运行时的类型,think in java这本书中,对泛型数组的处理通过四个小程序对其进行了比较完整的描述
程序一:这个程序主要说明了,在使用泛型数组中容易出现的问题,由于书中对于程序的说明比较详细,所以只对程序做引用
- class Generic<T> {
- }
-
- public class ArrayofGeneric {
- public static void main(String[] args) {
- Generic<Integer>[] genArr;
-
-
-
-
-
-
-
-
-
- genArr = (Generic<Integer>[]) new Generic[2];
- System.out.println(genArr);
- }
- }
|
程序二:这个程序主要是说明在程序的执行过程中,泛型数组的类型信息会被擦除,且在运行的过程中数组的类型有且仅有Object[],如果我们强制转换成T[]类型的话,虽然在编译的时候不会有异常产生,但是运行时会有ClassCastException抛出
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class ArrayOfGeneric2<T> {
- public T[] ts;
-
- public ArrayOfGeneric2(int size) {
- ts = (T[]) new Object[size];
- }
-
- public T get(int index) {
- return ts[index];
- }
-
- public T[] rep() {
- return ts;
- }
-
- public void set(int index, T t) {
- ts[index] = t;
- }
-
- public static void main(String[] args) {
- ArrayOfGeneric2<String> aog2 = new ArrayOfGeneric2<String>(10);
- Object[] objs = aog2.rep();
- System.out.println(objs);
-
-
-
- }
-
- }
|
评论暂时关闭