Delete an Element in the Middle of an Array
☰Fullscreen
Table of Content:
In Java, deleting an element from the middle of an array involves a few steps similar to inserting, as arrays have a fixed size. To delete an element, you will typically create a new array that is one element smaller than the original array, copy the elements over, and skip the element you want to remove.
Steps to Delete an Element in the Middle of an Array
- Create a new array with a size that is one less than the original array.
- Copy elements from the original array to the new array, skipping the element you want to delete.
Example Code
Here’s a complete Java program demonstrating how to delete an element from the middle of an array:
public class DeleteFromMiddleArray { public static void main(String[] args) { // Original array int[] originalArray = {10, 20, 30, 40, 50}; int positionToDelete = 2; // Index of the element to delete (middle) // Call the method to delete the element int[] newArray = deleteFromMiddle(originalArray, positionToDelete); // Print the new array System.out.println("New array after deletion:"); for (int num : newArray) { System.out.print(num + " "); } } public static int[] deleteFromMiddle(int[] array, int position) { // Create a new array with size one less than the original int[] newArray = new int[array.length - 1]; // Copy elements from the original array to the new array for (int i = 0; i < newArray.length; i++) { // Skip the element to be deleted if (i < position) { newArray[i] = array[i]; } else { newArray[i] = array[i + 1]; // Shift elements to the left } } return newArray; // Return the new array } }
Explanation of the Code
- Original Array: We start with an array that contains some initial elements.
- Delete Method: The
deleteFromMiddle
method takes the original array and the position of the element to delete. - New Array Creation: A new array is created that is one element smaller than the original array.
- Copying Elements: A loop is used to copy elements from the original array to the new array:
- If the current index is less than the position to delete, we copy the element normally.
- If the current index is greater than or equal to the position, we copy from the next index of the original array, effectively skipping the element to be deleted.
- Output: Finally, we print the new array to confirm that the element was deleted correctly.
Output
When you run the program, you will get the following output:
New array after deletion: 10 20 40 50
This shows that the element 30
at index 2
was successfully deleted from the original array.