To remove an element from an array at a specific index in Java, you can use the System.arraycopy
method to copy the elements of the array after the specified index to a new array, and assign the new array to the original array.
Here's an example of how you can do this:
int[] array = {1, 2, 3, 4, 5}; int index = 2; // The index of the element to remove // Create a new array with the elements after the specified index int[] newArray = new int[array.length - 1]; System.arraycopy(array, index + 1, newArray, index, array.length - index - 1); // Assign the new array to the original array array = newArray;
This code will remove the element at index 2 (the value 3) from the array
and assign the resulting array to the array
variable.
Note that this method does not preserve the order of the elements in the array, as the elements after the removed element are shifted to the left.
If you want to preserve the order of the elements, you can use a loop to copy the elements of the array to a new array, skipping the element at the specified index.
Here's an example of how you can do this:
int[] array = {1, 2, 3, 4, 5}; int index = 2; // The index of the element to remove // Create a new array with the same size as the original array int[] newArray = new int[array.length]; // Copy the elements of the array to the new array, skipping the element at the specified index int j = 0; for (int i = 0; i < array.length; i++) { if (i != index) { newArray[j++] = array[i]; } } // Assign the new array to the original array array = newArray;
This code will remove the element at index 2 (the value 3) from the array
and assign the resulting array to the array
variable, preserving the order.