How to delete a specific object in a Java array?
To remove a specific object from an array in Java, you can follow the steps below:
- Iterate through the array to find the index position of the object that needs to be deleted.
- Create a new array with a length one less than the original array.
- Copy the elements from the original array to a new array, excluding the ones that need to be deleted.
- Assign the new array to the original array.
Here is an example code:
public class Main {
public static void main(String[] args) {
// 原数组
String[] array = {"A", "B", "C", "D", "E"};
// 需要删除的对象
String target = "C";
// 查找需要删除的对象的索引位置
int targetIndex = -1;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(target)) {
targetIndex = i;
break;
}
}
// 如果找到了需要删除的对象
if (targetIndex != -1) {
// 创建新数组
String[] newArray = new String[array.length - 1];
// 将原数组中除需要删除的对象以外的元素复制到新数组中
int j = 0;
for (int i = 0; i < array.length; i++) {
if (i != targetIndex) {
newArray[j] = array[i];
j++;
}
}
// 将新数组赋值给原数组
array = newArray;
}
// 输出删除指定对象后的数组
for (String element : array) {
System.out.println(element);
}
}
}
In this example code, the original array is {“A”, “B”, “C”, “D”, “E”} and the object to be deleted is “C”. The output of running the code is:
A
B
D
E