Java loop to delete elements

When we are traversing the ArrayList, we need to delete the elements that meet the conditions. The general practice is as follows

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

for (int i = 0; i < list .size(); i++)
{            
    if (list .get(i).equals("hello"))
    {
        list .remove(i);
    }
}

But there will be a question in this approach: after this most common loop writing method is executed, it will find that the second "b" string is not deleted

or use for-each

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

for (String s : list)
{
    if (s.equals("b")) 
    {
        list.remove(s);
    }
}

This for-each writing method will report an exception java.util.ConcurrentModificationException.

In fact, the correct idea should be to use iterator, which is written as follows

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

Iterator<String> iter = list .iterator(); 

while(iter.hasNext()){  
    //新建一个对象
    String s = iter.next();  
    if(s.equals("hello")){  
        iter.remove();  
    }  
} 

Of course, there is another stupid method, without the convenience of iterator, that is, in the process of looping, adding all the elements that meet the conditions to a tempList, and then using the removeAll method to delete them together is also a good method.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325418894&siteId=291194637