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 🙁
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
nullto the array at the relevant position; e.g.This leaves you with the problem of dealing with the “holes” in the array where the
nullvalues 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.
The Apache Commons
ArrayUtilsclass 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
Collectiontype. For instance, theArrayListtype has a method that allows you to remove the element at a given position.