下面是 System.arrayCopy的源代碼聲明 :
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代碼解釋:
Object src : 原數(shù)組
int srcPos : 從元數(shù)據(jù)的起始位置開始
Object dest : 目標(biāo)數(shù)組
int destPos : 目標(biāo)數(shù)組的開始起始位置
int length : 要copy的數(shù)組的長度
比如 :我們有一個(gè)數(shù)組數(shù)據(jù) byte[] srcBytes = new byte[]{2,4,0,0,0,0,0,10,15,50}; // 源數(shù)組
byte[] destBytes = new byte[5]; // 目標(biāo)數(shù)組
我們使用System.arraycopy進(jìn)行轉(zhuǎn)換(copy)
System.arrayCopy(srcBytes,0,destBytes ,0,5)
上面這段代碼就是 : 創(chuàng)建一個(gè)一維空數(shù)組,數(shù)組的總長度為 12位,然后將srcBytes源數(shù)組中 從0位 到 第5位之間的數(shù)值 copy 到 destBytes目標(biāo)數(shù)組中,在目標(biāo)數(shù)組的第0位開始放置.
那么這行代碼的運(yùn)行效果應(yīng)該是 2,4,0,0,0
java中應(yīng)用舉例
java.util.concurrent中的CopyOnWriteArrayList類中的addAll()方法
/**
* Appends all of the elements in the specified collection to the end
* of this list, in the order that they are returned by the specified
* collection's iterator.
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
* @see #add(Object)
*/
public boolean addAll(Collection<? extends E> c) {
Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
if (cs.length == 0)
return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
if (len == 0 && cs.getClass() == Object[].class)
setArray(cs);
else {
Object[] newElements = Arrays.copyOf(elements, len + cs.length);
System.arraycopy(cs, 0, newElements, len, cs.length);
setArray(newElements);
}
return true;
} finally {
lock.unlock();
}
}