ArrayList.remove is not working in a loop

When you remove the first “Meg”, the index i=2. Then it’s incremented, but since one of the “Meg” is already removed, now name.get(3) is “Brain”. So you didn’t actually check the second “Meg”.

To fix the problem. you can decrement the index when you remove an element:

public class ArrayListExp{
    public static void main (String[] args){

        ArrayList<String> name = new ArrayList<String>();

        name.add("Chris");
        name.add("Lois");
        name.add("Meg");
        name.add("Meg");
        name.add("Brain");
        name.add("Peter");
        name.add("Stewie");

        System.out.println(name);

        for ( int i = 0;  i < name.size(); i++){
            String oldName = name.get(i);
            if(oldName.equals("Meg"))
            {
                name.remove(i);
                i--;
            }
        }

        System.out.println(name);
    }
}

Leave a Comment