1. Overview

In this quick tutorial, we’ll learn how to remove an element from an array in Java.

2. Removing an Element

Given the array below, let’s remove an element at index 2:

Array simple

A simple way of doing this would be to replace the value stored at index 2 with the value stored at index 3 until we reach the end of the array:

Array rm

Notice that by removing the element in the above manner, the size of the array would remain the same and the value stored at the last index would be empty. Since arrays have a fixed memory size allocated during initialization, removing an element does not adjust the size of the array.

Now let’s look at the array representation where we modify the size of the array:

Array rm common

As we can see, the array size here is adjusted to 5 after the element is removed. Usually, this approach creates a brand-new array and copies all the values except for the value being removed.

3. Removing the Given Element of an Array in Java

We can use the Apache Commons Lang library to remove the given element of an array. Let’s add the commons-lang3 dependency to our project’s pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

The ArrayUtils class provides two ways of removing an element from an array. Let’s look at these next.

3.1. Using Index as Input

The first way we can remove the given element is by its index with ArrayUtils#remove:

public int[] removeAnElementWithAGivenIndex(int[] array, int index) {
    return ArrayUtils.remove(array, index);
}

Another variation is the removeAll method, which we can use to remove multiple elements from an array, given their indices:

public int[] removeAllElementsWithGivenIndices(int[] array, int... indices) {
    return ArrayUtils.removeAll(array, indices);
}

3.2. Using Element as Input

Or, let’s say we don’t know the index of what we are removing. In that case, we can provide the element to remove using ArrayUtils#removeElement:

public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) {
    return ArrayUtils.removeElement(array, element);
}

Here’s another useful variation of this method ArrayUtils#removeElements, in case there is more than one element that we would like to remove:

public int[] removeAllGivenElements(int[] array, int... elements) {
    return ArrayUtils.removeElements(array, elements);
}

4. Removing the Last Element From an Array in Java

4.1. Using Arrays.CopyOf() Method

We can also use the Arrays class copyOf() method, which creates a new array by copying the specified array and truncating it to the specified new length, which in this case would be the original array length minus one:

public int[] removeLastElementCopyOf(int[] array) {
    return Arrays.copyOf(array, array.length - 1);
}

4.2. Using Arrays.CopyOfRange() Method

Next, let’s try to use the copyOfRange() method, which allows copying a specified range from the original array into a new array. In this new array, the range would be from the start of the array to the second-to-last elements:

public int[] removeLastElementCopyOfRange(int[] array) {
    return Arrays.copyOfRange(array, 0, array.length - 1);
}

4.3. Using System.arraycopy() Method

The System.arraycopy() is a native method for copying the elements of the original array into the new array, excluding the last element. We’ll use this method to create a new array with a length one less than the original array and copy all elements except the last one.

The method takes five parameters: the source array, the starting position in the source array, the destination array, the starting position in the destination array, and the number of elements to be copied:

public int[] removeLastElementUsingArrayCopyMethod(int[] array, int[] resultArray) {
    System.arraycopy(array, 0, resultArray, 0, array.length-1);
    return resultArray;
}

4.4. Using IntStream.Range() Method

The IntStream.range() method allows us to create a stream of integers within a specified range, which we can then map to the elements of the original array, excluding the last element:

public int[] removeLastElementUsingIntStreamRange(int[] array) {
    return IntStream.range(0, array.length - 1)
      .map(i -> array[i])
      .toArray();
}

4.5. Using Apache Commons Lang

We can also use the previously discussed removeAnElementWithAGivenIndex() method to remove the last element of an array. Let’s see this method in action:

@Test
void givenIndex_whenUsingApacheCommonsLang_thenRemoveLastElement() {
    int lastElementIndex = inputArray.length - 1;
    int[] modifiedArray = sut.removeAnElementWithAGivenIndex(inputArray, lastElementIndex);
    assertEquals(modifiedArray.length, inputArray.length - 1);
    assertFalse(ArrayUtils.contains(modifiedArray, inputArray[lastElementIndex]));
}

5. Conclusion

In this article, we looked at the various ways of removing an element from an array.

To learn more about the edge cases, please check out the source code for this tutorial and the relevant unit tests over on GitHub.


« 上一篇: Spring @qualifier注释
» 下一篇: Thymeleaf 中枚举使用