How to remove strings of certain lengths

Posted by Macosx Iam on Stack Overflow See other posts from Stack Overflow or by Macosx Iam
Published on 2011-11-17T01:44:18Z Indexed on 2011/11/17 1:50 UTC
Read the original article Hit count: 132

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays