Java Examples - Delete Array Elements
Arrays in Java have a fixed length and cannot be directly deleted. We can create a new array and put the elements we want to keep from the original array into the new array:
Main.java File
import java.util.Arrays;
public class ExampleTest {
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, that is, delete the third element, 5
int[] newArray = new int[oldarray.length-1];//New array, with a length equal to the original array minus 1
for(int i=0;i<newArray.length; i++) {
//Check whether 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 contents of the array
System.out.println(Arrays.toString(oldarray));
oldarray = newArray;
System.out.println(Arrays.toString(oldarray));
}
}
The above code produces the following output:
[3, 4, 5, 6, 7] [3, 4, 6, 7]
We can also use ArrayList to implement this functionality. ArrayList is a dynamic array, making operations more convenient.
The following example demonstrates how to use ArrayList's remove() method to remove elements from the ArrayList:
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,"The 0th element");
objArray.add(1,"The 1st element");
objArray.add(2,"The 2nd element");
System.out.println("Before removing the element from the array:"+objArray);
objArray.remove(1);
objArray.remove("The 0th element");
System.out.println("After removing the element from the array:"+objArray);
}
}
The above code produces the following output:
数组删除元素前:[第 0 个元素, 第 1 个元素, 第 2 个元素] 数组删除元素后:[第 2 个元素]Other Extensions
Java Examples