To delete an element from an array in Java, you can use one of the following approaches:
int[] array = {1, 2, 3, 4, 5}; int[] newArray = new int[array.length - 1]; int index = 2; // the index of the element to be deleted for (int i = 0, j = 0; i < array.length; i++) { if (i == index) { continue; } newArray[j++] = array[i]; }
This will create a new array newArray
that is one element shorter than the original array and contains all the elements of the original array except for the element at the specified index.
System.arraycopy
method to copy the elements of the array before and after the element to be deleted:int[] array = {1, 2, 3, 4, 5}; int index = 2; // the index of the element to be deleted System.arraycopy(array, 0, array, 0, index); System.arraycopy(array, index + 1, array, index, array.length - index - 1);