在Java中,由于数组的大小是固定的,不能直接删除数组中的元素。但是,可以通过以下几种方法来删除数组中的元素:
使用`System.arraycopy()`方法
int[] arr = {1, 2, 3, 4, 5};System.arraycopy(arr, 3, arr, 2, arr.length - 3);// arr数组现在为{1, 2, 4, 5}
使用`Arrays.copyOf()`方法
int[] arr = {1, 2, 3, 4, 5};arr = Arrays.copyOf(arr, arr.length - 1);// arr数组现在为{1, 2, 3, 4}
使用`ArrayList`的`remove()`方法 (如果数组存储在`List`对象中):

Listlist = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); list.remove(2);// list现在为[1, 2, 4, 5]
自定义方法删除数组中的元素
public static int[] removeElement(int[] arr, int indexToRemove) {int[] newArray = new int[arr.length - 1];System.arraycopy(arr, 0, newArray, 0, indexToRemove);System.arraycopy(arr, indexToRemove + 1, newArray, indexToRemove, arr.length - indexToRemove - 1);return newArray;}// 使用示例int[] arr = {1, 2, 3, 4, 5};arr = removeElement(arr, 2);// arr数组现在为{1, 2, 4, 5}
以上方法都可以用来删除数组中的元素,但请注意,这些方法并不会改变原始数组的大小。如果删除了数组中的最后一个元素,原始数组的大小仍然保持不变。
