使用泛型對java數組擴容,java數組擴容

來源:互聯網
上載者:User

使用泛型對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 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.