How to remove given object from an Array in Java?
Last Updated :
18 Jan, 2023
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"}
Explanation: 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
// 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]);
}
}
}
OutputUpdated array:-
for
hello
world
Time Complexity: O(N), where N is length of array.
Auxiliary Space: O(1)
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
// 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]);
}
}
}
OutputUpdated array:-
for
hello
world
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
SQL Interview Questions Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970's, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read