System.arraycopy方法


數組的復制有多種方法,其中有一種就是System.arraycopy方法,傳聞速度也很快.

方法完整簽名:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

參數

@ src -- 這是源數組 @ srcPos -- 這是源數組中的起始位置 @dest -- 這是目標數組 @ destPos -- 這是目標數據中的起始位置  @ length -- 這是一個要復制的數組元素的數目

ex.

int arr1[] = {0,1,2,3,4,5}; int arr2[] = {0,10,20,30,40,50}; System.arraycopy(arr1,0,arr2,1,2);
結果:arr2 = [0,0,1,30,40,50];
System.arraycopy方法經常與Array類中的newInstance(Creates a new array with the specified component type and length)方法一起使用,如:
public static Object copyOf(Object a,int newLength){ Class cl = a.getClass(); if(!cl.isArray()) return null; Class componentType =cl.getComponentType(); int length = Array.getLength(a); Object newArray = Array.newInstance(componentType,newLength); System.arraycopy(a,0,newArray,0,Math.min(length,newLength)); return newArray;
}

這里說明一下,接收參數是Object對象,在調用Array.newInstance的時候,產生的數組類型是componentType,即與接收參數相同的類型,意味着最終返回的Object對象可以強制轉換成與原數組類型相同的新數組對象,達到新建拷貝的目的,上面是通用拷貝的寫法.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM