前言:看 ArrayList 的源码,发现 remove 方法主要依赖了 System.arraycopy() 方法实现的。所以需要了解一下这个方法如何使用。转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9951819.html
源码
带注释的源码:
/**
* Copies an array from the specified source array, beginning at the
* specified position, to the specified position of the destination array.
* A subsequence of array components are copied from the source
* array referenced by <code>src</code> to the destination array
* referenced by <code>dest</code>. The number of components copied is
* equal to the <code>length</code> argument. The components at
* positions <code>srcPos</code> through
* <code>srcPos+length-1</code> in the source array are copied into
* positions <code>destPos</code> through
* <code>destPos+length-1</code>, respectively, of the destination
* array.
* <p>
* If the <code>src</code> and <code>dest</code> arguments refer to the
* same array object, then the copying is performed as if the
* components at positions <code>srcPos</code> through
* <code>srcPos+length-1</code> were first copied to a temporary
* array with <code>length</code> components and then the contents of
* the temporary array were copied into positions
* <code>destPos</code> through <code>destPos+length-1</code> of the
* destination array.
* <p>
* If <code>dest</code> is <code>null</code>, then a
* <code>NullPointerException</code> is thrown.
* <p>
* If <code>src</code> is <code>null</code>, then a
* <code>NullPointerException</code> is thrown and the destination
* array is not modified.
* <p>
* Otherwise, if any of the following is true, an
* <code>ArrayStoreException</code> is thrown and the destination is
* not modified:
* <ul>
* <li>The <code>src</code> argument refers to an object that is not an
* array.
* <li>The <code>dest</code> argument refers to an object that is not an
* array.
* <li>The <code>src</code> argument and <code>dest</code> argument refer
* to arrays whose component types are different primitive types.
* <li>The <code>src</code> argument refers to an array with a primitive
* component type and the <code>dest</code> argument refers to an array
* with a reference component type.
* <li>The <code>src</code> argument refers to an array with a reference
* component type and the <code>dest</code> argument refers to an array
* with a primitive component type.
* <
不带注释的源码:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
参数解释:
src: 源数组;
srcPos: 源数组要复制的起始位置;
dest: 目的数组;
destPos: 目的数组放置的起始位置;
length: 复制的长度。
从源码注释中就可以看出
1、拷贝过程:将 src 数组的下标为 srcPos 到 srcPos + length - 1 拷贝到 dest 数组下标为 destPos 到 destPos + length- 1 的位置。
2、这个也支持 src 和 dest 为同一个数组,这时会将原数组拷贝到临时数组里,然后再将临时数组的数据拷贝到目标数组。
3、如果 src 或者 dest 为 null ,则会抛空指针异常。
4、如果 src 或者 dest 不是数组,则会抛出 ArrayStoreException。
5、src,dest 不是同类型或者可以进行转换的数组,则会抛出 ArrayStoreException。
6、如果 srcPos + length > length或者 destPos + lenght > length,则会抛出 IndexOutOfBoundsException。
测试:
转载请注明出处:https://www.cnblogs.com/yuxiaole/p/9951819.html