Remove Element from an Array in Java

Introduction

This tutorial will go through some common techniques for removing elements from Java arrays. Manipulating array elements is an extremely common task as discussions about it can be found on many forums, particularly on StackOverflow.

Here's a list of the techniques and methods we'll go over in this article:

A Short Briefing on Arrays

Arrays are data structures common in many programming languages. Each array is stored in a single block of memory and it allows sequential storage and simple manipulation of elements:

java array in memory

Credit: CodeForWin

Elements are sequentially stored one after another. When someone wants to access an element at a certain index, pointer arithmetic (which is the mechanism under the hood) allows to quickly and efficiently obtain any particular element.

If the index of a requested element is 3, the underlying mechanism simply needs to take the memory address of the zero-th element and add three times the size of each element. Since all array elements have the same size, this kind of computation leads directly to the element with index 3. Furthermore, this happens in O(1) complexity which means it's as fast as it can be.

What makes removing an array element difficult is the fact that all elements are stored sequentially in a single memory block. Due to the nature of array's memory placement, it is simply impossible to remove the element directly.

Instead, to "remove" any element, all subsequent elements need to be shifted backward by one place. This will create an illusion that a specific element was removed.

Using Two Arrays

The simplest pure Java way to do this is to make a new array, one element shorter than the original one and copy all element, except the one we'd like to remove, into it:

int[] copy = new int[array.length - 1];

for (int i = 0, j = 0; i < array.length; i++) {
    if (i != index) {
        copy[j++] = array[i];
    }
}

Here, we're simply iterating over the original array and copying elements from the original array into the new array, skipping the one we'd like to remove.

The copy array now consists of:

10, 20, 30, 50, 60, 70, 80, 90, 100

ArrayUtils.remove()

In case you're already using the Apache Commons library, you can use the ArrayUtils.remove() method.

Before working with Apache Commons, we'll want to add it to our project:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>${version}</version>
</dependency>

Using the method is really simple. We simply supply it with the array we'd like to remove an element from and its index:

int[] array = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int index = 3;
array = ArrayUtils.remove(array, index);

It then returns the new array, which is stored in the array variable:

10, 20, 30, 50, 60, 70, 80, 90, 100

Using a for loop

The seemingly simplest way to remove an element is to iterate the array manually using a for loop. Alternatively, a while loop can also be used but for is much more suitable for this type of task.

Say, we want to remove the third element:

int[] array = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int index = 3;

The element corresponding to index 3 is 40. To remove this element, we simply "shift" all elements after it. This means that we're going to iterate through all the elements after 40 and simply "move" them one place to the left.

Since it's not possible to just move an element, we copy its value instead. Subsequent copies will overwrite original values and the result will be as if the entire right part of the array was shifted leftward by one:

for (int i = index; i < array.length - 1; i++) {
    array[i] = array[i + 1];
}

If we went and printed the modified array, this would be the result:

10, 20, 30, 50, 60, 70, 80, 90, 100, 100

Arrays are of fixed length. The last element, 100, is duplicated because of this. Using a single array, it's impossible to remove an element without filling the new gap with some value.

You could override it with a dummy value, such as -1, but this solution isn't very valid. This is eliminated by Using Two Arrays.

System.arraycopy

A shorthand way of doing the exact same thing as before but in a single line of code is with the System.arraycopy() method:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

The method accepts a source array and the position from which to start copying. It also accepts a destination array and the position into which to start copying. The final argument is the number of elements to copy from the source array.

The arraycopy is generally used to copy contents from some source array into some destination array. Though, we can also copy an array, or a part of it, into itself. This allows us to shift a part of it to the left like last time:

int[] array = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int index = 3;

To remove the element, we only need to write this one line of code:

System.arraycopy(array, index + 1, array, index, array.length - index - 1);

The method will copy all elements from the source array (array) starting one position right of the index. The elements will be copied into the same array (array) starting exactly at index. The result will be a perceived shifting of all elements right of the element we wanted to remove.

If we printed the result, we would still see the element 100 being duplicated for the same reason as in the previous section. In the next section, we'll show how to eliminate this problem completely.

Conclusion

In this tutorial, we showed a few ways of removing array elements. Some are quick and dirty, whereas some require additional overhead such as using additional libraries. It's always best to think about these things beforehand to get the idea of what kind of approach is right for any given situation.

The list of techniques shown in this tutorial is by no means exhaustive. There are plenty of ways to get creative in programming so we're sure you can find some other interesting approaches to remove elements from arrays.

Author image
About Luka Čupić
Croatia Website