使用泛型對java數組擴容,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 }