JAVA remove elements from a list in a loop

JAVA remove elements from a list in a loop

Consider the following piece of code that deletes multiple elements in a loop

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(int i=0;i<list.size();i++){
    list.remove(i);
}
System.out.println(list);

The output is:

[b,d]

There is a serious bug in this method. When an element is removed, the size of the list shrinks and the subscript changes, so when you want to remove multiple elements with subscripts in a loop, it doesn't work properly.

You probably know that the correct way to delete multiple elements in a loop is to use iteration, and you know that a foreach loop in java looks like an iterator, but it's not. Consider the following code:

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
for(String s:list){
    if(s.equals("a")){
        list.remove(s);
    }
}

It throws a ConcurrentModificationException.

Instead the following display works fine:

ArrayList<String> list = new ArrayList<String>(Arrays.asList("a","b","c","d"));
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
        String s = iter.next();
        if(s.equals("a")){
            iter.remove();
    }
}

.next()Must be .remove()called before. In a foreach loop, the compiler will cause .next() to be called after removing an element, thus throwing a ConcurrentModificationException, you might want to take a look at the source code of ArrayList.iterator().

Guess you like

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