Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
1. Removing an Element from an Array Using a For Loop
2.1.
Step-by-Step Explanation
2.2.
Example Code
2.3.
Java
3.
2. Deleting an Array Element by Its Value
3.1.
Detailed Steps
3.2.
Example Code
3.3.
Java
4.
3. Deleting an Element by Its Value When the Array Contains Duplicates
4.1.
Detailed Steps
4.2.
Example Code
4.3.
Java
5.
4. Shifting Elements in the Same Array
5.1.
Detailed Steps
5.2.
Example Code
5.3.
Java
6.
5. Deleting Elements from an ArrayList
6.1.
Detailed Steps
6.2.
Example Code
6.3.
Java
7.
Frequently Asked Questions
7.1.
What happens if I try to remove an element that is not in the array?
7.2.
Can I remove elements from an array without creating a new array?
7.3.
Is there a difference in performance between using arrays and ArrayLists for removing elements?
8.
Conclusion
Last Updated: May 25, 2024
Medium

Remove an Element From an Array in Java

Author Riya Singh
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Arrays are a fundamental data structure in Java that allow you to store multiple elements of the same data type and manipulating arrays is a fundamental skill for any Java programmer, often involving operations such as removing elements.

Remove an Element From an Array in Java

In this article, we'll learn about the  different ways to remove elements from an array in Java, including using a for loop, deleting an element by its value, handling duplicate elements, shifting elements within the array, & deleting elements from an ArrayList.

1. Removing an Element from an Array Using a For Loop

One of the most straightforward methods to remove an element from an array in Java is by using a for loop. This approach involves shifting each element of the array to the left to overwrite the element you wish to remove. Let's break down the steps and dive into a specific example to make this clear.

Step-by-Step Explanation

  1. Identify the Target Element: First, determine the index of the element you want to remove. This index is crucial as it tells us where to start modifying the array.
     
  2. Shift Elements: Starting from the identified index, shift each subsequent element one position to the left. This effectively overwrites the element you're removing.
     
  3. Resize the Array: Since arrays in Java have a fixed size, you'll need to create a new array if you want to adjust the array's size after removal. Alternatively, you can set the last element to null or a default value if resizing isn't necessary.

Example Code

Here’s a simple example to illustrate removing an element from an array using a for loop:

  • Java

Java

public class ArrayRemovalExample {
public static void main(String[] args) {
int[] originalArray = {1, 2, 3, 4, 5}; // Initial array
int removeIndex = 2; // Index of element to remove, i.e., '3'

// Loop to shift elements left from the specified index
for (int i = removeIndex; i < originalArray.length - 1; i++) {
originalArray[i] = originalArray[i + 1];
}

// Optional: Set the last element to a default value
originalArray[originalArray.length - 1] = 0; // Assuming 0 as the default value

// Displaying the modified array
for (int value : originalArray) {
System.out.print(value + " ");
}
}
}

Output

1 2 4 5 0 


In this example, after identifying the element '3' to be removed (at index 2), each subsequent element is shifted one position to the left. The last element is then set to zero, as resizing the array isn't directly possible without creating a new array.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

2. Deleting an Array Element by Its Value

Sometimes, you might need to remove an element from an array based on its value rather than its position. This method requires searching for the value first and then removing it using a similar shifting technique as described previously. Here’s how you can do it effectively.

Detailed Steps

  1. Find the Value: Loop through the array to find the first occurrence of the target value. Note the index where this value is found.
     
  2. Shift Elements to Remove the Value: Once the target value is found, shift all subsequent elements one position to the left, starting from this index.
     
  3. Handle the Last Element: Since the size of the array cannot be reduced dynamically, you can set the last element to a default value, such as null or 0, depending on the array type.

Example Code

Here is a code example that demonstrates how to delete an element by its value:

  • Java

Java

public class ArrayValueRemovalExample {
public static void main(String[] args) {
int[] originalArray = {7, 8, 9, 10, 9}; // Initial array
int valueToRemove = 9; // Value to remove

// Finding the index of the first occurrence of the value to remove
int indexToRemove = -1;
for (int i = 0; i < originalArray.length; i++) {
if (originalArray[i] == valueToRemove) {
indexToRemove = i;
break;
}
}

// If the value is found, shift subsequent elements left
if (indexToRemove != -1) {
for (int i = indexToRemove; i < originalArray.length - 1; i++) {
originalArray[i] = originalArray[i + 1];
}
originalArray[originalArray.length - 1] = 0; // Setting last element to default value
}

// Display the modified array
for (int value : originalArray) {
System.out.print(value + " ");
}
}
}

Output

7 8 10 9 0 


This code locates the first occurrence of the value 9 and removes it by shifting the subsequent values. It is particularly useful when you know the value to be removed but not its position.

3. Deleting an Element by Its Value When the Array Contains Duplicates

When working with arrays that contain duplicate values, removing an element based on its value can be a bit more complex, especially if you need to remove all occurrences of that value. This method ensures that every duplicate value is removed effectively.

Detailed Steps

  1. Identify All Occurrences: Iterate through the array and mark the indices where the target value occurs.
     
  2. Shift Elements: For each marked index, shift the subsequent elements to the left. This might require adjusting the array multiple times depending on the number of duplicates.
     
  3. Adjust the Array Size: Set the end elements of the array to a default value if you are not resizing the array, to reflect the removal of duplicates.

Example Code

Here’s how you can implement the removal of all duplicates of a specific value in an array:

  • Java

Java

public class DuplicateValueRemoval {
public static void main(String[] args) {
int[] originalArray = {11, 12, 11, 13, 11}; // Initial array with duplicates
int valueToRemove = 11; // Value to remove

// We need to find out how many times the value occurs
int count = 0;
for (int value : originalArray) {
if (value != valueToRemove) {
originalArray[count++] = value;
}
}

// Set the remaining elements to a default value
while (count < originalArray.length) {
originalArray[count++] = 0; // Assuming 0 is the default value
}

// Display the modified array
for (int value : originalArray) {
System.out.print(value + " ");
}
}
}


In this example, the array initially contains three occurrences of the value 11. The program loops through the array, copying over only those values that are not 11 to the beginning of the array. This effectively removes all duplicates and fills the end of the array with 0.

4. Shifting Elements in the Same Array

Shifting elements within an array is a key operation, especially after removing one or more elements. This technique involves moving elements to new positions within the same array without creating a new array. It's useful for maintaining the order of elements and optimizing space usage.

Detailed Steps

  1. Determine the Shift Start: Identify the point in the array from which you need to start shifting elements. This is usually the index after an element has been removed.
     
  2. Execute the Shift: Move each element from the start point to the end of the array one position to the left. This closes the gap created by the removed element.
     
  3. Handle the Array's End: The last element of the array will need to be set to a default value since it will be duplicated after the shift.

Example Code

Here is a simple example demonstrating how to shift elements within the same array:

  • Java

Java

public class ElementShifting {
public static void main(String[] args) {
int[] array = {14, 15, 16, 17, 18}; // Initial array
int indexToRemove = 2; // We remove the element at index 2, which is '16'

// Shifting elements left from the index after the removed element
for (int i = indexToRemove; i < array.length - 1; i++) {
array[i] = array[i + 1];
}

// Setting the last element to a default value
array[array.length - 1] = 0; // Assuming 0 as the default value

// Displaying the modified array
for (int value : array) {
System.out.print(value + " ");
}
}
}

Output

[22, 23, 24]

In this example, after removing the element '16', each subsequent element is shifted left to fill the gap. The last element is then set to zero to avoid duplication.

5. Deleting Elements from an ArrayList

Working with Java's ArrayList offers more flexibility compared to arrays, particularly when it comes to removing elements. ArrayList automatically adjusts its size when items are added or removed, making it ideal for situations where you need dynamic array management.

Detailed Steps

  1. Use the remove() Method: ArrayList provides the remove() method, which can be used to remove elements either by their index or by the object itself.
     
  2. Handling Duplicates: If the list contains duplicates, remove() will only delete the first occurrence. To remove all occurrences, you can use a loop or stream API.
     
  3. Ensure List Integrity: After removing elements, the list automatically compacts its size, so no manual adjustment of capacity is necessary.

Example Code

Here's an example demonstrating how to remove elements from an ArrayList, including handling multiple occurrences of a value:

  • Java

Java

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListRemoval {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(20, 21, 22, 23, 24, 20));

// Removing a single element by value - removes the first '20'
numbers.remove(Integer.valueOf(20));

// Removing an element by index - removes the element at index 0 (now '21')
numbers.remove(0);

// To remove all occurrences of '20'
numbers.removeAll(Arrays.asList(20));

// Displaying the modified ArrayList
System.out.println(numbers);
}
}

Output

[22, 23, 24]


In this code, we start by removing the first occurrence of 20 and then the element at index 0. To remove all occurrences of 20, we use the removeAll() method with an Arrays.asList() containing the value to be completely eliminated.

Frequently Asked Questions

What happens if I try to remove an element that is not in the array?

If you attempt to remove an element that doesn't exist in the array, your code won't make any changes to the array. However, it's good practice to check if the element exists before trying to remove it to avoid potential errors.

Can I remove elements from an array without creating a new array?

While you can shift elements within the array to overwrite unwanted elements, the size of the array remains unchanged unless you explicitly create a new array with the reduced size.

Is there a difference in performance between using arrays and ArrayLists for removing elements?

Yes, ArrayLists are generally more efficient for operations that involve frequent insertion and deletion because they automatically adjust their size. Arrays, however, are more performant for fixed-size data operations and accessing elements by index.

Conclusion

In this article, we've learned various methods to remove elements from arrays & ArrayLists in Java. We started with basic for loops for simple removals, advanced to handling values directly, tackled duplicates, and shifted elements within arrays. We also discussed the dynamic capabilities of ArrayLists that simplify removals and automatically manage array sizes. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.
 

Previous article
Varargs in Java(Variable Arguments)
Next article
Difference‌ ‌between‌ ‌Java ‌and‌ ‌JavaScript
Live masterclass