可以通过三种方法从 Java 数组中移除元素:1. 使用 Arrays.copyOfRange() 创建指定范围内的数组,排除目标元素;2. 将数组转换为 ArrayList,使用 remove() 方法移除目标元素,再转换回数组;3. 使用 System.arraycopy() 手动复制元素,覆盖目标元素。

如何从 Java 数组中移除元素
开门见山:可以使用以下方法从 Java 数组中移除元素:
详细说明:
1. 使用 Arrays.copyOfRange()
立即学习“Java免费学习笔记(深入)”;
Arrays.copyOfRange() 函数会创建一个包含指定范围内元素的新数组,同时排除目标元素。
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = Arrays.copyOfRange(arr, 0, 3); // 从数组中移除元素 4 和 52. 使用 ArrayList
将数组转换为 ArrayList,使用 remove() 方法移除目标元素,然后将 ArrayList 转换回数组。
int[] arr = {1, 2, 3, 4, 5};
List list = new ArrayList<>(Arrays.asList(arr));
list.remove(new Integer(4)); // 从数组中移除元素 4
int[] newArr = list.stream().mapToInt(i -> i).toArray(); 3. 使用 System.arraycopy()
使用 System.arraycopy() 函数手动将元素从目标位置复制到新数组中,从而覆盖目标元素。
int[] arr = {1, 2, 3, 4, 5};
int[] newArr = new int[arr.length - 1];
System.arraycopy(arr, 0, newArr, 0, 3);
System.arraycopy(arr, 4, newArr, 3, 1); // 从数组中移除元素 4注意:
- 对于基本类型数组,移除元素会导致数组大小缩小。
- 对于对象数组,移除元素不会缩小数组大小,而是将目标元素设置为空。











