mirror of
https://github.com/Snailclimb/JavaGuide
synced 2025-06-16 18:10:13 +08:00
Update ArrayList源码+扩容机制分析.md
对 ArrayList 中的 System.arraycopy() 和 Arrays.copyOf() 添加说明
This commit is contained in:
parent
8b1ffa70ed
commit
86b2ddf14e
@ -733,6 +733,24 @@ public class ArrayList<E> extends AbstractList<E>
|
||||
|
||||
#### 3.3.1. `System.arraycopy()` 方法
|
||||
|
||||
源码:
|
||||
|
||||
```java
|
||||
// 我们发现 arraycopy 是一个 native 方法,接下来我们解释一下各个参数的具体意义
|
||||
/**
|
||||
* 复制数组
|
||||
* @param src 源数组
|
||||
* @param srcPos 源数组中的起始位置
|
||||
* @param dest 目标数组
|
||||
* @param destPos 目标数组中的起始位置
|
||||
* @param length 要复制的数组元素的数量
|
||||
*/
|
||||
public static native void arraycopy(Object src, int srcPos,
|
||||
Object dest, int destPos,
|
||||
int length);
|
||||
```
|
||||
|
||||
场景:
|
||||
```java
|
||||
/**
|
||||
* 在此列表中的指定位置插入指定的元素。
|
||||
@ -781,6 +799,21 @@ public class ArraycopyTest {
|
||||
|
||||
#### 3.3.2. `Arrays.copyOf()`方法
|
||||
|
||||
源码:
|
||||
|
||||
```java
|
||||
public static int[] copyOf(int[] original, int newLength) {
|
||||
// 申请一个新的数组
|
||||
int[] copy = new int[newLength];
|
||||
// 调用System.arraycopy,将源数组中的数据进行拷贝,并返回新的数组
|
||||
System.arraycopy(original, 0, copy, 0,
|
||||
Math.min(original.length, newLength));
|
||||
return copy;
|
||||
}
|
||||
```
|
||||
|
||||
场景:
|
||||
|
||||
```java
|
||||
/**
|
||||
以正确的顺序返回一个包含此列表中所有元素的数组(从第一个到最后一个元素); 返回的数组的运行时类型是指定数组的运行时类型。
|
||||
|
Loading…
x
Reference in New Issue
Block a user