Java 中数组分割方法:Arrays.copyOfRange() 方法:复制指定范围元素创建新数组。System.arraycopy() 方法:将指定范围元素复制到新数组中。

如何在 Java 中分割数组
方法:
-
使用 Arrays.copyOfRange() 方法:
- 此方法可复制数组中指定范围内的元素,创建新数组。
-
使用 System.arraycopy() 方法:
立即学习“Java免费学习笔记(深入)”;
- 此方法可将指定范围内的数组元素复制到新数组中。
步骤:
Arrays.copyOfRange() 方法:
- 导入
java.util.Arrays包。 -
调用
Arrays.copyOfRange(array, startIndex, endIndex),其中:-
array是要分割的原始数组。 -
startIndex是新数组开始元素的索引(包含)。 -
endIndex是新数组结束元素的索引(不包含)。
-
示例:
int[] numbers = {1, 2, 3, 4, 5, 6};
int[] subArray = Arrays.copyOfRange(numbers, 2, 4);System.arraycopy() 方法:
- 导入
java.lang.System包。 -
调用
System.arraycopy(srcArray, srcPos, destArray, destPos, length),其中:-
srcArray是要分割的原始数组。 -
srcPos是原始数组中开始复制元素的索引。 -
destArray是存储分割后元素的目标数组。 -
destPos是目标数组中存储开始复制元素的索引。 -
length是要复制的元素数量。
-
示例:
int[] numbers = {1, 2, 3, 4, 5, 6};
int[] subArray = new int[3];
System.arraycopy(numbers, 2, subArray, 0, 3);











