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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
[If you want some ready-to-use code, please scroll to my ‘Edit3’ (after the cut). The rest is here for posterity.]
To flesh out Dustman’s idea:
Edit: I’m now using
Arrays.asListinstead ofCollections.singleton: singleton is limited to one entry, whereas theasListapproach allows you to add other strings to filter out later:Arrays.asList('a', 'b', 'c').Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:
Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:
Then the function becomes:
This will then stop littering your heap with useless empty string arrays that would otherwise be
newed each time your function is called.cynicalman’s suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:
I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling
size()on the wrong list).