How to Remove an Element from Array in Java with Example

There is no direct way to remove elements from an Array in Java. Though Array in Java objects, it doesn't provide any methods to add(), remove() or search an element in Array. This is the reason Collection classes like ArrayList and HashSet are very popular. Thanks to Apache Commons Utils, You can use there ArrayUtils class to remove an element from array more easily than by doing it yourself. One thing to remember is that Arrays are fixed size in Java, once you create an array you can not change their size, which means removing or deleting an item doesn't reduce the size of the array. This is, in fact, the main difference between Array and ArrayList in Java.

What you need to do is create a new array and copy remaining content of this array into a new array using System.arrayCopy() or any other means. In fact, all other API and functions you will use do this but then you don't need to reinvent the wheel. 

For an Object or Reference arrays, you can also convert Array to List and then remove a particular object and convert List back to the array. One way to avoid this hassle is by using ArrayList instead of Array in the first place.

Btw, if you are a complete beginner in Java world and don't know much about Java API, particularly Java Collection framework which provides ready-made classes for common data structure like array, list, set, hash table, stack, queue etc, I suggest you to first go through The Complete Java Master Class course on Udemy.

It's one of the most comprehensive course and covers Java from length to breadth. It's also the most up-to-date course and recently updated for latest Java version.





How to delete an element from Array in Java

Here is a complete code example of how to remove an element from Array in Java. In this example, we have used a primitive array, particularly int array and Apache commons ArrayUtils to remove an integer based on its index.

The ArrayUtils also provided several overloaded remove() method for the different type of primitive arrays like int, long, float and double.

Btw, if you are not familiar with array data structure itself, like it stores elements in contiguous memory location, provides fast search capability in O(1) time if you know the index and adding and removing elements is very difficult then I also suggest you go through a comprehensive  data structure and algorithm course like Data Structures and Algorithms: Deep Dive Using Java on Udemy.

How to Remove an Element from Array in Java with Example


It's one of the most important topics and you just cannot afford to ignore it. This is also your first steps towards becoming a better computer Programmer you always wanted to be.

Anyway, here is our Java program to delete an array from a primitive array in Java:

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

/**
 *
 * Java program to show how to remove element from Array in Java
 * This program shows How to use Apache Commons ArrayUtils
 * to delete elements from primitive array.
 *
 * @author http://java67.com
 */

public class RemoveObjectFromArray{

    public static void main(String args[]) {
                 
        //let's create an array for demonstration purpose
        int[] test = new int[] { 101, 102, 103, 104, 105};
     
        System.out.println("Original Array : size : "
                               + test.length );
        System.out.println("Contents : " + Arrays.toString(test));
     
        // let's remove or delete an element from an Array
        // using Apache Commons ArrayUtils

        test = ArrayUtils.remove(test, 2); //removing element at index 2
     
        // Size of an array must be 1 less than the original array
        // after deleting an element

        System.out.println("Size of the array after
                  removing an element  : "
+ test.length);
        System.out.println("Content of Array after
                 removing an object : " 
+ Arrays.toString(test));
     
    }
 
}

Output:
Original Array : size : 5
Contents : [101, 102, 103, 104, 105]
Size of the array after removing an element  : 4
Content of Array after removing an object : [101, 102, 104, 105]


That's all on How to remove an element from Array in Java. You can create your own method to delete objects from Array as well but ArrayUtils is tried and tested by Java community and offer a convenient way to delete an element from Array in Java. It’s always better to leverage a library method instead of creating new in Java development.


Further Learning
The Complete Java Master Class
Data Structures and Algorithms: Deep Dive Using Java 
Introduction to Algorithms by Thomas H. Corman


Other Data Structure and Algorithms  You may like
  • How to reverse an array in Java? (solution)
  • How to remove duplicate elements from the array in Java? (solution)
  • 50+ Data Structure and Algorithms Problems from Interviews (list)
  • 5 Books to Learn Data Structure and Algorithms in depth (books
  • How to implement a binary search tree in Java? (solution)
  • Post order binary tree traversal without recursion (solution)
  • How to implement a recursive preorder algorithm in Java? (solution)
  • 100+ Data Structure Coding Problems from Interviews (questions)
  • How to print leaf nodes of a binary tree without recursion? (solution)
  • How to remove duplicate elements from an array without using API? (solution)
  • Iterative PreOrder traversal in a binary tree (solution)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • 75+ Coding Interview Questions for Programmers (questions)
  • Recursive InOrder traversal Algorithm (solution)
  • Recursive Post Order traversal Algorithm (solution)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)

Thanks for reading this article so far. If you like this Java Array tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Easy to Advanced Data Structures course on Udemy. It's authored by a Google Software Engineer and Algorithm expert and its completely free of cost.

18 comments:

  1. thanks for the post

    ReplyDelete
  2. THIS IS USELESS import org.apache.commons.lang.ArrayUtils; DOESN'T NAME A TYPE IN A PACKAGE.

    ReplyDelete
  3. Yeah.. THIS IS USELESS (import org.apache.commons.lang.ArrayUtils;) doesn't recognize by the package.

    ReplyDelete
  4. You don't have to import the ArrayUtils class, it comes from the java.lang package which means it can be used without importing.. Just cancel the second import and your code should work just fine

    ReplyDelete
  5. it doesnt come in java.lang pkg...not working

    ReplyDelete
  6. You need the apache commons JAR file in your build path of course....

    impost org.apache.commons.lang.ArrayUtils;

    ReplyDelete
  7. it is not there in java package and we ned to add dependency or add jar in classpath which is apache commons

    ReplyDelete
  8. thanks for this post, i would appreciate if u could give a hint about solving this problem (remove an element from an array) without using collections(ArrayList etc)

    ReplyDelete
  9. This is something which cant be considered as the best solution. Lets have a look on my below mentioned code:
    public class DeletionFromArray {

    public static int[] deleteArray(int arr[], int i )
    {

    for(int j =i;j<arr.length - 1;j++)
    {
    arr[j]= arr[j+1];
    }
    return arr;
    }

    public static void main(String[] args) {

    int input[] = {20, 10, 2, 4, 3};
    int output[] = deleteArray(input, 1);
    System.out.println(output.length);
    for(int k=0; k<output.length - 1;k++)
    {
    System.out.println(output[k]);
    }

    }

    }

    ReplyDelete
  10. I guess in some of these questions they won't want you to use inbuilt classes and all. Here is a way to get it done with plain primitives.


    static int removeElement(int [] arr, int elem) {
    int length = 0;
    System.out.println(Arrays.toString(arr));

    for (int i = 0; i < arr.length; i++) {
    if (arr[i] != elem) arr[length++] = arr[i];
    }

    System.out.println(Arrays.toString(Arrays.copyOf(arr, length)));
    return length;
    }

    ReplyDelete
    Replies
    1. You are my saviour! i just imported java.util.Arrays; and this worked flawlessly!

      Delete
  11. this does't works for me.what do we have to import

    ReplyDelete
  12. Object myStore= new Object[10];
    int actSize=myStore.length-1;
    public Object remove(int index){
    if(index<actSize){
    Object obj=myStore[index];
    myStore[index]=null;
    int temp=index;
    while(temp<actSize){
    myStore[temp]=myStore[temp++];
    myStore[temp+1]=null;
    temp++;
    }
    }actSize--;
    return obj;

    }

    ReplyDelete
  13. This function will remove the index element and return the new array:

    public static int[] removeElement(int[] arr, int index){

    int[] newArr = new int[arr.length-1];
    int j = 0;
    for(int i = 0; i<arr.length; i++){
    if(i != index){
    newArr[j] = arr[i];
    j++;
    }

    }
    return newArr;
    }

    ReplyDelete
  14. You can also use the delete operator. The delete operator in JavaScript behaves a bit differently than you might think. Delete removes the property from an object, what this means in English is that instead of physically removing the item, its value is set to undefined.

    Ex.

    var fish = ['goldfish', 'carp', 'guppy', 'cod'];
    // Remove the value at index 2
    delete fish[2]; // delete the guppy!

    console.log(fish);
    // Result: ['goldfish', 'carp', undefined, 'cod']

    ReplyDelete
    Replies
    1. That's nice but does that changes the length of the array or array length is still the same?

      Delete