Array Deletion
Array deletion refers to the process of removing an element from an array. In Java, when you delete an element from an array, you need to shift all the elements that come after the deleted element to fill the gap.
Here's an example of how to delete an element from an array:
1public class ArrayDeletion {
2 public static void main(String[] args) {
3 // Create an array
4 int[] numbers = {1, 2, 3, 4, 5};
5 int deleteIndex = 2;
6
7 // Shift elements to remove the specified index
8 for (int i = deleteIndex; i < numbers.length - 1; i++) {
9 numbers[i] = numbers[i + 1];
10 }
11
12 // Reduce the length of the array by 1
13 int[] newArray = new int[numbers.length - 1];
14 for (int i = 0; i < newArray.length; i++) {
15 newArray[i] = numbers[i];
16 }
17
18 // Print the updated array
19 System.out.println(Arrays.toString(newArray));
20 }
21}
In this example, we have an array numbers
with elements [1, 2, 3, 4, 5]. We want to delete the element at index 2.
To delete the element, we start by shifting all the elements after the deleted element one position to the left. This is done in the for loop, where we start from the delete index and move towards the end of the array. Each element is replaced with the element at the next index, effectively removing the element at the delete index.
After shifting the elements, we create a new array with a length one less than the original array. We copy all the elements from the original array to the new array, excluding the last element, which was shifted off.
Finally, we print the updated array to verify the deletion.
Array deletion is a common operation when working with arrays. It allows you to remove specific elements from the array and adjust the array size accordingly.
xxxxxxxxxx
public class ArrayDeletion {
public static void main(String[] args) {
// Create an array
int[] numbers = {1, 2, 3, 4, 5};
int deleteIndex = 2;
// Shift elements to remove the specified index
for (int i = deleteIndex; i < numbers.length - 1; i++) {
numbers[i] = numbers[i + 1];
}
// Reduce the length of the array by 1
int[] newArray = new int[numbers.length - 1];
for (int i = 0; i < newArray.length; i++) {
newArray[i] = numbers[i];
}
// Print the updated array
System.out.println(Arrays.toString(newArray));
}
}