日期:2014-05-20 浏览次数:20933 次
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; //目前Java不支持泛型数组。底层的数组类型只能是object的.可以通过java反射来模拟实现 class GenericArray<T> { private T[] oneDimensionArray; T[][] twoDimensionArray; public GenericArray(Class<T> type, int size) { oneDimensionArray = (T[]) Array.newInstance(type, size); } public GenericArray(Class<T> type, int rows , int cols){ twoDimensionArray = (T[][]) Array.newInstance( type, rows, cols); } public void put(int index, T item) { oneDimensionArray[index] = item; } public void put(int rows , int cols, T item) { twoDimensionArray[rows][cols] = item; } public T get(int index) { return oneDimensionArray[index]; } public T get(int rows , int cols) { return twoDimensionArray[rows][cols]; } } public class TestGenericArray{ public static void main(String[] args) { System.out.println("\n---测试一维“泛型数组”---"); GenericArray<List> oneDimension = new GenericArray<List>( List.class, 3); for(int i=0; i<3; i++){ oneDimension.put(i,new ArrayList<Integer>(Arrays.asList(i))); } for(int i=0; i<3; i++){ System.out.print(oneDimension.get(i) + " "); } System.out.println("\n---测试二维“泛型数组”---"); GenericArray<List> twoDimension = new GenericArray<List>( List.class, 3, 3); for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ twoDimension.put(i,j,new ArrayList<Integer>(Arrays.asList(i, j))); } } for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ System.out.print(twoDimension.get(i,j) + " "); } System.out.println(); } } } /* ---测试一维“泛型数组”--- [0] [1] [2] ---测试二维“泛型数组”--- [0, 0] [0, 1] [0, 2] [1, 0] [1, 1] [1, 2] [2, 0] [2, 1] [2, 2] */