Remove Element From an Array in Java

In this post we’ll see how to remove or delete element from an array in Java. You have several options to do that task of removing an element from an array.

  1. Write your own logic.
  2. Use ArrayList to remove an element. You will need to convert array to ArrayList and then back to array.
  3. Use Apache Commons library. In that library there is a ArrayUtils class that has remove method for that purpose.
  4. You can also use System.arraycopy() method for removing element from an array.

Writing your own logic

If you have to write your own Java program to remove element from an array then you will have to shift all the elements, to the left, that come after the element that has to be removed. Another thing that you will have to consider is; once created array is of fixed length so after shifting all the elements there will still be one space left in the array and that space will be filled by repeating the last element. Let’s see with an example.

Java Program to remove element from an array

Output

You can see the empty space after shifting the elements is filled by repeating the last element.

What you can do is to create another array of size one less than the original array. After shifting the elements you can copy element from the original array to the new array, leaving the last element. For copying the array you can use System.arraycopy() method.

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)– Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. The number of components copied is equal to the length argument.

Output

As you can see now the problem of extra element is resolved.

Using System.arraycopy() method to delete array element

You can use System.arraycopy() method to remove element from an array in Java. Once you know the index of the element that has to be removed you can call System.arraycopy() method twice, once for copying the element from 0 till the index and then from index + 1 till the end of the array.

Java code

Output

Using ArrayUtils class in Apache Commons

You can also use ArrayUtils.remove method in ArrayUtils class to remove element from an array in Java. For that you will have to have Apache commons jar in classpath.

Java code

Output

Converting array to ArrayList to remove element from array

You can convert array to ArrayList and then remove the element from that ArrayList. After removal of element you can convert ArrayList back to array.

Output

That’s all for the topic Remove Element From an Array in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.