How to delete elements from an array?


To delete an element at a particular position from an array. Starting from the required position, replace the element in the current position with the element in the next position.

Example

 Live Demo

public class DeletingElementsBySwapping {
public static void main(String args[]) {
int [] myArray = {23, 93, 56, 92, 39};
System.out.println("hello");

int size = myArray.length;
int pos = 2;

for (int i = pos; i<size-1; i++) {
myArray[i] = myArray[i+1];
}

for (int i=0; i<size-1; i++) {
System.out.println(myArray[i]);
}
}
}

Output

hello
23
93
92
39

Alternate solution

Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project.

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

This package provides a class known as ArrayUtils. Using the remove()method of this class instead of swapping elements, you can delete them.

Example

import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class DeletingElements {
public static void main(String args[]) {
int [] myArray = {23, 93, 56, 92, 39};
int [] result = ArrayUtils.remove(myArray, 2);
System.out.println(Arrays.toString(result));
}
}

Output

[23, 93, 92, 39]

Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.

Updated on: 16-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements