From 86b2ddf14e29df2d110ec62adcd7dcbaadb2b839 Mon Sep 17 00:00:00 2001 From: ly <37680485+drlifeL@users.noreply.github.com> Date: Sat, 29 May 2021 15:16:32 +0800 Subject: [PATCH] =?UTF-8?q?Update=20ArrayList=E6=BA=90=E7=A0=81+=E6=89=A9?= =?UTF-8?q?=E5=AE=B9=E6=9C=BA=E5=88=B6=E5=88=86=E6=9E=90.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对 ArrayList 中的 System.arraycopy() 和 Arrays.copyOf() 添加说明 --- .../ArrayList源码+扩容机制分析.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/java/collection/ArrayList源码+扩容机制分析.md b/docs/java/collection/ArrayList源码+扩容机制分析.md index 1a04914f..cd717572 100644 --- a/docs/java/collection/ArrayList源码+扩容机制分析.md +++ b/docs/java/collection/ArrayList源码+扩容机制分析.md @@ -733,6 +733,24 @@ public class ArrayList extends AbstractList #### 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 /** 以正确的顺序返回一个包含此列表中所有元素的数组(从第一个到最后一个元素); 返回的数组的运行时类型是指定数组的运行时类型。