What is ArrayUtils.remove in Java?

remove is a static method of the ArrayUtils class that removes the element at a given index.

  • Once the element at the specified index is removed, all the subsequent elements are shifted by one position to the left in the array.
  • The index value cannot be negative.
  • The index value cannot be more than the number of elements in the array.

Example 1

  • array = [1,2,3,4,5]
  • index = 2

Application of the remove function will result in the following array: [1,2,4,5].

Once the element is removed from the index 2, all the subsequent elements are shifted by one position to the left in the array.

ArrayUtils is defined in the Apache Commons Lang package. To add Apache Commons Lang to the Maven Project, add the following dependency to the pom.xml file.

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

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the ArrayUtils class as follows.

import org.apache.commons.lang3.ArrayUtils;

Syntax

public static int[] remove(int[] array, int index)

Parameters

  • int[] array: array of elements.
  • int index: position of the element to be removed.

Return value

The method returns a new array with the element at the specified index removed.

Code

import org.apache.commons.lang3.ArrayUtils;
public class Main {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
System.out.print("Original Array - ");
for(int i: array){
System.out.print(i + " ");
}
int[] result = ArrayUtils.remove(array, 2);
System.out.print("\nModified Array after removing element at index 2 - ");
for(int i: result){
System.out.print(i + " ");
}
}
}

Expected output

Original Array - 1 2 3 4 5 
Modified Array after removing element at index 2 - 1 2 4 5

Free Resources