Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element from an array

Tags:

java

arrays

I have an array for example:

String [][] test = {{"a","1"},
                    {"b","1"},
                    {"c","1"}};

Can anyone tell me how to remove an element from the array. For example I want to remove item "b", so that the array looks like:

{{"a","1"},
 {"c","1"}}

I can't find a way of doing it. What I have found here so far is not working for me :(

like image 360
Peter Avatar asked May 09 '11 09:05

Peter


People also ask

Can you delete elements from an array?

Java arrays do not provide a direct remove method to remove an element. In fact, we have already discussed that arrays in Java are static so the size of the arrays cannot change once they are instantiated. Thus we cannot delete an element and reduce the array size.

Can you remove an element from an array in C?

In C programming, an array is derived data that stores primitive data type values like int, char, float, etc. To delete a specific element from an array, a user must define the position from which the array's element should be removed. The deletion of the element does not affect the size of an array.

How do you delete an element from an index array?

Answer: Use the splice() Method You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount) .


1 Answers

You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:

  • Assign null to the array at the relevant position; e.g.

    test[1] = null;
    

    This leaves you with the problem of dealing with the "holes" in the array where the null values are. (In some cases this is not a problem ... but in most cases it is.)

  • Create a new array with the element removed; e.g.

    String[][] tmp = new String[test.length - 1][];
    int j = 0;
    for (int i = 0; i < test.length; i++) {
        if (i != indexOfItemToRemove) {
            tmp[j++] = test[i];
        }
    }
    test = tmp;
    

    The Apache Commons ArrayUtils class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int), but the fact remains that this approach creates a new array object.

A better approach would be to use a suitable Collection type. For instance, the ArrayList type has a method that allows you to remove the element at a given position.

like image 95
Stephen C Avatar answered Sep 21 '22 15:09

Stephen C