Given an array arr of N objects, the task is to remove all the occurrences of a given object from the array in Java.
Example:
Input: String[] arr = { “Geeks”, “for”, “Geeks”, “hello”, “world” }, removeObj = “Geeks”
Output: updated arr[] = {“for”, “hello”, “world”}
Expalanation: All the occurrences of removeObj has been removed from the array.
Methods to remove objects from an array in Java are:
There are generally two methods to remove objects from an array in java, which are:
1. Using java.util.Arrays.copyOf method in Java:
java.util.Arrays.copyOf() method copies the given array to a specified length. We will use this method to remove all the occurrences of a given object from the array. The idea is to skip all the elements equal to the object to be removed (i.e., removeObj) and shift the rest of the objects to the left of the array. Then by using copyOf() method we will make the copy of the array to the last index where the last object not equal to removeObj has been shifted.
Below is the implementation for the above approach:
Java
|
Updated array:- for hello world
2. Using java.util.Arrays.asList() method in Java:
java.util.Arrays.asList() method is used to return a fixed-size list backed by the specified array. It makes a List out of the array. We will first convert the given array to List using Arrays.asList() method. Now the List interface in Java has a method as removeAll() to remove all the occurrences of the given element (i.e., removeObj) from the list. After that, we convert that list back to array by toArray() method.
Below is the implementation:
Java
|
Updated array:- for hello world