如何在Java中从数组中删除给定的对象?
给定一个由 N个 对象组成的数组,任务是在Java中删除数组中所有出现的给定对象。
例子。
输入。String[] arr = { "Geeks", "for", "Geeks", "hello", "world" }, removeObj = "Geeks"
**Output:**updated arr[] = {"for", "hello", "world" }
Expalanation: 所有removeObj的出现都已从数组中删除。
在Java中从数组中删除对象的方法有。
在Java中从数组中删除对象的方法一般有两种,分别是。
1.使用Java中的java.util.Arrays.copyOf方法。
java.util.Arrays.copyOf()方法将给定的数组复制到一个指定的长度。我们将使用该方法从数组中删除所有给定对象的出现。我们的想法是跳过所有与要删除的对象相等的元素(即removeObj),将其余的对象移到数组的左边。然后,通过使用copyOf() 方法,我们将把数组复制到最后一个不等于removeObj 的对象被转移的索引处。
下面是上述方法的实现。
Java
// Java Program to remove a given
// object from the array
import java.util.Arrays;
public class Main {
public static void main(String args[])
{
// Given an array of String objects
String[] arr
= { "Geeks", "for", "Geeks", "hello", "world" };
// object to be removed
String removeObj = "Geeks";
// Here variable i is used to store
// the element as ith index
// variable j is iterated over
// complete array to find the removeObj
int i, j;
for (i = 0, j = 0; j < arr.length; j++)
// Check if jth object is
// not equal to removeObj
if (!arr[j].equals(removeObj)) {
// If jth object is not equal to
// removeObj then it is
// inserted at ith index
arr[i++] = arr[j];
}
// Making arr equal to copyof
// of itself till ith index
arr = Arrays.copyOf(arr, i);
// Print the updated array
System.out.println("Updated array:- ");
for (int ind = 0; ind < arr.length; ind++) {
System.out.println(arr[ind]);
}
}
}
输出
Updated array:-
for
hello
world
2.在Java中使用java.util.Arrays.asList()方法。
java.util.Arrays.asList()方法用于返回一个由指定数组支持的固定大小的列表。它从数组中生成一个列表。我们将首先使用Arrays.asList()方法将给定的数组转换为List。现在Java中的List接口有一个 removeAll()方法,可以从列表中移除所有给定元素的出现(即removeObj)。之后,我们通过**toArray()**方法将列表转换为数组。
下面是实现方法。
Java
// Java Program to remove a
// given object from the array
import java.util.*;
public class Main {
public static void main(String args[])
{
// Given an array of String objects
String[] arr
= { "Geeks", "for", "Geeks", "hello", "world" };
// object to be removed
String removeObj = "Geeks";
// Converting the array to list
List<String> list
= new ArrayList<String>(Arrays.asList(arr));
// Remove all occurrences of given string
list.removeAll(Arrays.asList(removeObj));
// Convert back list to array
// the length of array
// will also be updated
arr = list.toArray(new String[0]);
// Print the updated array
System.out.println("Updated array:- ");
for (int ind = 0; ind < arr.length; ind++) {
System.out.println(arr[ind]);
}
}
}
输出
Updated array:-
for
hello
world