編寫一個通用方法,其功能是將數組擴展到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 }