public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
這是一個native方法最終交給jni層處理,用來拷貝數組
參數說明:
- src 數據源數組,需要從哪個數組拷貝數據
- srcPos 從src數據的那個位置開始拷貝
- dest 目標數組,把src里面的數據拷貝到這里
- destPos 開始填充數據的下標位置
- length 從src數據中拷貝多少個數據
列子:
int[] original = {0,1,2,3,4,5,6,7,8,9};
int[] copy = {0,1,2,3,4,5,6,7,8,9,0,0};
System.arraycopy(original, 4, copy, 5, original.length-4);
copy[4] = 123;
for(int item:copy) {
System.out.print(item + ",");
}
將數組original數據的第4個位置開始拷貝,一共拷貝length-4個數組,依次從copy數組第五個開始存放。
輸出:
0,1,2,3,123,4,5,6,7,8,9,0
這個就是ArrayList.add(index , E) 的實現原理:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
ArrayList在插入數據的時候先要進行擴容(如果有需要),然后拷貝數組,所以說ArrayList如果有頻繁插入和刪除的操作的話會非常消耗性能的,建議使用LinkedList。LinkedList是一個雙向鏈表結構,插入數據快,查找數據慢。