Java Example - Removing Array Elements
Java arrays have a fixed length and cannot be directly deleted. We can achieve this by creating a new array and placing the elements we want to keep from the original array into the new array:
Main.java File
import java.util.Arrays;
public class tutorialproTest {
public static void main(String[] args) {
int[] oldarray = new int[] {3, 4, 5, 6, 7}; // Original array
int num = 2; // Delete the element at index 2, which is the third element 5
int[] newArray = new int[oldarray.length-1]; // New array, length is one less than the original array
for(int i=0; i<newArray.length; i++) {
// Check if the element is out of bounds
if (num < 0 || num >= oldarray.length) {
throw new RuntimeException("Element out of bounds... ");
}
//
if(i<num) {
newArray[i] = oldarray[i];
}
else {
newArray[i] = oldarray[i+1];
}
}
// Print the array content
System.out.println(Arrays.toString(oldarray));
oldarray = newArray;
System.out.println(Arrays.toString(oldarray));
}
}
The output of the above code is:
[3, 4, 5, 6, 7]
[3, 4, 6, 7]
We can also use ArrayList to achieve this functionality, as ArrayList is a dynamic array and is more convenient to operate with.
The following example demonstrates how to use the remove()
method of ArrayList to delete elements from the array list:
Main.java File
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> objArray = new ArrayList<String>();
objArray.clear();
objArray.add(0,"Element 0");
objArray.add(1,"Element 1");
objArray.add(2,"Element 2");
System.out.println("Array before element removal: " + objArray);
objArray.remove(1);
objArray.remove("Element 0");
System.out.println("Array after element removal: " + objArray);
}
}
The output of the above code is:
Array before element removal: [Element 0, Element 1, Element 2]
Array after element removal: [Element 2]