How to remove strings of certain lengths
- by Macosx Iam
So I have this array, and I want to delete strings that are 2 or 4 characters in length (strings that contain 2 or 4 characters). I am doing this method, and it doesn't work, even though logically, it SHOULD work.
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("This");
list.add("is");
list.add("a");
list.add("test");
for (int i=0; i<list.size(); i++)
{
if(list.get(i).length()==2 || list.get(i).length()==4)
{
list.remove(i);
}
}
}
I'd like to stick to this method of doing it. Can you please give me some suggestions as to how to correct this code?
The output of this code when I run it is:
[is, a]
Even though I want the output to be
[a]
because "is" is 2 characters long.