Java program to Remove element from array

In this post, we will see how to remove an element from array in java.
Unlike Arraylist,Java Arrays class does not provide any direct method to add or delete element. As Array is fixed size in nature, you can not shrink or grow it dynamically. You need to create new array and copy all elements except the element which you want to remove.

If you have no duplicates in array, you can simply use Apache common’s ArrayUtil class.It has removeElement method which removes first occurence of the element from the array and return new array.

Remove element from array with inbuilt functon

You can also use Apache common’s ArrayUtils.removeElement(array, element) method to remove element from array. It will remove first occurence of element in the array.It is cleaner and elegant way to remove any element from array.
Step 1: Create a simple java maven project.
Step 2: Add Apache common dependency to pom.xml.

Step 3: Create a class named "RemoveElementApacheCommonMain"

When you run above program, you will get below output:

Before removing element
1 34 2 23 35 65
============
After removing element 23
1 34 2 35 65

Remove element from array without inbuilt functon

You are given an array and element.You need to remove all the occurrences of the element in the array and return its new length.
You should not use any extra space and without inbuilt function

If you are not allowed to use any inbuild function, you can use below algorithm.

  • Let’s say your array is arr[] and length=0
  • Iterate over array and if element is equal to arr[i], skip the iteration(as we need to remove the element) else increment the length and assign current element.
  • When i reaches to last element, you will get newLength and all instances of element will be removed.

Let’s see with the help of simple program.

Create a class named "RemoveElementMain".

When you run above program, you will get below output:

Before removing element
1 34 23 2 23 35 65
============
After removing element 23
1 34 2 35 65

That’s all about removing element from array in java.

Was this post helpful?

Leave a Reply

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