How to remove an item from an array

I have an array, for example:

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

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

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

I can not find a way to do this. What I found here is not working for me yet :(

+5
source share
4 answers

You cannot remove an element from an array. The size of the Java array is determined by the distribution of the array and cannot be changed. The best you can do is:

  • Assign the nullarray to the appropriate position; eg.

    test[1] = null;
    

    "" , null. ( ... .)

  • ; .

    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;
    

    Apache Commons ArrayUtils , (, Object[] ArrayUtils.remove(Object[], int), .

Collection. , ArrayList , .

+10

"" Java.

, ArrayList.

+6

null (test[0][1] = null;). "" , , , . , ArrayList ( Collection ).

+2

:

= > , - .

No need assign null to the array at the relevant position; e.g.

test[1] = null;

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

String[][] temp = new String[test.length - 1][];

/ : IndexToRemove

for (int i = 0; i < test.length-1; i++) {
                if (i<IndexToRemove){
                    temp[i]=test[i];
                }else if (i==IndexToRemove){
                    temp[i]=test[i+1];
                }else {
                    temp[i]=test[i+1];
                }
}
test = temp;

, !

0

All Articles