How to remove an element from a Java array?
In Java, the length of an array is fixed and cannot be changed once it is created. However, you can achieve the effect of deleting an element by creating a new array and excluding the element you want to remove. One common method to delete an element from an array is as follows:
public static int[] removeElement(int[] arr, int index) {// 创建一个新的数组,长度比原数组少1
int[] newArr = new int[arr.length - 1];
// 将原数组中除了要删除的元素之外的其他元素复制到新数组中
for (int i = 0, j = 0; i < arr.length; i++) {
if (i != index) {
newArr[j++] = arr[i];
}
}
return newArr;
}
Example Usage:
public static void main(String[] args) {int[] arr = {1, 2, 3, 4, 5};
int index = 2; // 要删除的元素的索引
int[] newArr = removeElement(arr, index);
// 输出新数组
for (int i = 0; i < newArr.length; i++) {
System.out.print(newArr[i] + " ");
}
}
The output result is 1 2 4 5, which means the element 3 at index 2 has been removed.