Java数组无法直接插入元素,因其内存连续且长度固定;所谓插入需创建新数组并手动复制前后段元素,或改用ArrayList自动处理扩容与位移。

Java 中的数组是固定长度的,无法直接在指定位置插入新元素。要实现“插入”效果,必须创建一个新数组,将原数组中指定位置前后的元素分别复制过去,并把新元素放在目标位置。
为什么不能直接插入?
数组在内存中占用连续空间,创建后长度不可变。所谓“插入”,本质是重新组织数据并扩容,需要手动处理元素移动和新数组创建。
手动实现插入逻辑(推荐初学理解)
以 int[] 为例,在索引 index 处插入值 value:
- 检查 index 是否合法(0 ≤ index ≤ 原数组长度,允许插到末尾)
- 新建长度为 原长度 + 1 的数组
- 用 System.arraycopy 或循环,将原数组 [0, index) 段复制到新数组开头
- 将 value 赋给新数组的 index 位置
- 将原数组 [index, 原长度) 段复制到新数组的 [index+1, 新长度) 位置
示例代码:
立即学习“Java免费学习笔记(深入)”;
public static int[] insert(int[] arr, int index, int value) {
if (index < 0 || index > arr.length) {
throw new IllegalArgumentException("Index out of bounds");
}
int[] newArr = new int[arr.length + 1];
System.arraycopy(arr, 0, newArr, 0, index); // 前半段
newArr[index] = value; // 插入元素
System.arraycopy(arr, index, newArr, index + 1, arr.length - index); // 后半段
return newArr;
}用 ArrayList 替代(实际开发更常用)
如果频繁增删,应优先使用 ArrayList,它内部封装了动态扩容和位移逻辑:
- add(int index, E element) 直接在指定位置插入
- 自动处理扩容、元素移动,无需手动管理数组长度
- 底层仍是数组,但对开发者透明
示例:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 4, 5)); list.add(2, 3); // 在索引2处插入3 → [1, 2, 3, 4, 5]
注意事项
- 原始数组本身不会改变,返回的是新数组或新集合
- 插入时间复杂度为 O(n),因为可能需移动大量元素
- 若需高性能随机插入/删除,考虑 LinkedList(但不支持 O(1) 随机访问)
- 泛型数组(如 String[])插入逻辑相同,只需替换类型和 new 数组语句


















