Given an array of n Objects, let's say it is an array of strings, and it has the following values:
foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
What do I have to do to delete/remove all the strings/objects equal to "a" in the array?
My little contribution to this problem.
}
You can use external library:
It is in project Apache Commons Lang http://commons.apache.org/lang/
Make a
List
out of the array withArrays.asList()
, and callremove()
on all the appropriate elements. Then calltoArray()
on the 'List' to make back into an array again.Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.
If you need to remove multiple elements from array without converting it to
List
nor creating additional array, you may do it in O(n) not dependent on count of items to remove.Here,
a
is initial array,int... r
are distinct ordered indices (positions) of elements to remove:Small testing:
In your task, you can first scan array to collect positions of "a", then call
removeItems()
.You can always do: