使用泛型对java数组扩容

编写一个通用方法,其功能是将数组扩展到10%+10个元素(转载请注明出处)

 1 package cn.reflection;
 2 
 3 import java.lang.reflect.Array;
 4 
 5 public class ArrayGrowTest {
 6     public static void main(String[] args){
 7         ArrayGrowTest growTest=new ArrayGrowTest();
 8         int[] aInt={1,2,3,4};
 9         System.out.print("原数组:");
10         growTest.printArray(aInt);
11         aInt=(int[]) growTest.goodArrayGrow(aInt);
12         System.out.print("扩容后数组:");
13         growTest.printArray(aInt);
14         
15         String[] aStr={"hello","world","ni","hao","ma"};
16         System.out.print("原数组:");
17         growTest.printArray(aStr);
18         aStr=(String[]) growTest.goodArrayGrow(aStr);
19         System.out.print("扩容后数组:");
20         growTest.printArray(aStr);
21     }
22     /**
23      * 数组扩容方法,支持不同数组类型
24      * @param a  原数组
25      * @return newArray 新数组
26      */
27     public Object goodArrayGrow(Object a){
28         Class cl=a.getClass();
29         if(!cl.isArray()){
30             return null;
31         }
32         Class componentType=cl.getComponentType();   //使用Class类的getComponentType方法确定数组对应的类型
33         int length=Array.getLength(a);   //原长度
34         int newLength=length*11/10+10;   //新长度
35         Object newArray=Array.newInstance(componentType, newLength);  //实例化新数组
36         //为新数组赋值,a代表原数组,第一个0代表原数组复制起始位置,newArray代表新数组,第二个0代表新数组放值起始位置,length代表从原数组中复制多长到新数组
37         System.arraycopy(a, 0, newArray, 0, length);  
38         return newArray;
39     }
40     /**
41      * 输出数组内容
42      * @param a 需要输出的数组
43      */
44     public void printArray(Object a){
45         Class cl=a.getClass();
46         if(!cl.isArray()){
47             return ;
48         }
49         Class componentType=cl.getComponentType();  
50         int length=Array.getLength(a);
51         System.out.print(componentType.getName()+"["+length+"]={");
52         for(int i=0;i<length;i++){
53             System.out.print(Array.get(a, i)+ " ");
54         }
55         System.out.println("}");
56     }
57 
58 }

 

posted @ 2016-09-19 11:24  lhxiao  阅读(625)  评论(0)    收藏  举报