remove
is a static method of the ArrayUtils
class that removes the element at a given index.
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 theApache Commons Lang
package. To addApache Commons Lang
to the Maven Project, add the following dependency to thepom.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;
public static int[] remove(int[] array, int index)
int[] array
: array of elements.int index
: position of the element to be removed.The method returns a new array with the element at the specified index removed.
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 + " ");}}}
Original Array - 1 2 3 4 5
Modified Array after removing element at index 2 - 1 2 4 5