数组作为 Java 中最基础的数据结构,其固定长度的特性使得增删操作需要特殊处理。本文将基于数组查找功能,一步步实现元素插入(单个元素 / 数组)和删除操作,带你掌握数组操作的核心技巧。
基础:数组元素查找
首先,我们需要实现一个基础功能 ------ 查找指定元素在数组中的位置。这是后续所有操作的前提。
查找功能实现
java
/**
* 查找数组中指定元素的位置
*
* @param arr 待查找的数组
* @param target 要查找的目标元素
* @return 元素所在索引,未找到返回-1
*/
public static int findElement(int[] arr, int target) {
// 空数组直接返回-1
if (arr == null || arr.length == 0) {
return -1;
}
// 遍历数组查找元素
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i; // 找到元素,返回索引
}
}
return -1; // 未找到元素
}
进阶操作一:在指定元素后插入单个元素
代码实现
java
/**
* 在指定元素后插入单个新元素
*
* @param arr 原数组
* @param target 目标元素(在其后插入)
* @param newValue 要插入的新元素
* @return 插入后的新数组
*/
public static int[] insertAfterElement(int[] arr, int target, int newValue) {
int targetIndex = findElement(arr, target);
// 未找到目标元素,返回原数组副本
if (targetIndex == -1) {
int[] newArr = new int[arr.length];
System.arraycopy(arr, 0, newArr, 0, arr.length);
return newArr;
}
// 创建新数组,长度+1
int[] newArr = new int[arr.length + 1];
// 复制目标元素及之前的元素
System.arraycopy(arr, 0, newArr, 0, targetIndex + 1);
// 插入新元素
newArr[targetIndex + 1] = newValue;
// 复制目标元素之后的元素
System.arraycopy(arr, targetIndex + 1, newArr, targetIndex + 2,
arr.length - targetIndex - 1);
return newArr;
}
进阶操作二:在指定元素后插入数组
有时候我们需要插入多个元素,这就需要在指定位置插入一个数组。
代码实现
java
/**
* 在指定元素后插入一个数组的所有元素
*
* @param arr 原数组
* @param target 目标元素(在其后插入)
* @param insertArr 要插入的数组
* @return 插入后的新数组
*/
public static int[] insertArrayAfterElement(int[] arr, int target, int[] insertArr) {
if (insertArr == null || insertArr.length == 0) {
return arr.clone(); // 插入数组为空,返回原数组副本
}
int targetIndex = findElement(arr, target);
// 未找到目标元素,返回原数组副本
if (targetIndex == -1) {
return arr.clone();
}
// 创建新数组,长度=原数组长度+插入数组长度
int[] newArr = new int[arr.length + insertArr.length];
// 复制目标元素及之前的元素
System.arraycopy(arr, 0, newArr, 0, targetIndex + 1);
// 插入新数组
System.arraycopy(insertArr, 0, newArr, targetIndex + 1, insertArr.length);
// 复制目标元素之后的元素
System.arraycopy(arr, targetIndex + 1, newArr,
targetIndex + 1 + insertArr.length,
arr.length - targetIndex - 1);
return newArr;
}
进阶操作三:删除指定元素
代码实现
java
/**
* 删除数组中的指定元素
*
* @param arr 原数组
* @param target 要删除的目标元素
* @return 删除后的新数组
*/
public static int[] deleteElement(int[] arr, int target) {
int targetIndex = findElement(arr, target);
// 未找到目标元素,返回原数组副本
if (targetIndex == -1) {
return arr.clone();
}
// 创建新数组,长度-1
int[] newArr = new int[arr.length - 1];
// 复制目标元素之前的元素
System.arraycopy(arr, 0, newArr, 0, targetIndex);
// 复制目标元素之后的元素
System.arraycopy(arr, targetIndex + 1, newArr, targetIndex,
arr.length - targetIndex - 1);
return newArr;
}
总结
本文通过数组查找、插入、删除三大操作的实现,展示了 Java 数组操作的核心技巧:
- 查找是基础:所有定位操作都依赖于元素查找功能
- 增删靠复制:数组长度固定,增删操作本质是创建新数组并分区域复制元素
- 分段处理是关键:无论是插入还是删除,都需要将数组分为目标位置前后两部分分别处理