java - Why does removing the last element in foreach report an error?
PHP中文网
PHP中文网 2017-05-17 10:04:40
0
5
877
public static void main(String[] args) {

        List<String> a = new ArrayList<String>();
            
        a.add("1");
        a.add("2");
        a.add("23");
        for (String temp : a) {
            if ("23".equals(temp)) {
                a.remove(temp);
            }
        }
        System.out.println(a);
    }

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at wan.ForEach.main(ForEach.java:22)

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
大家讲道理

foreach是通过迭代器来实现的,使用迭代器遍历元素时,容器不能试图改变容器的结构,如remove、add操作会抛出异常; 可以使用迭代器的removeMethod to delete elements.

迷茫

http://tyrion.iteye.com/blog/...

漂亮男人

The person above made it very clear. Here I will tell you two simple solutions
1. Iterator deletion
2. Copy the list to traverse, and then operate the original list.
Of course iterator deletion is recommended

phpcn_u1582

What is said upstairs is very official. To put it bluntly, the method of for(Object obj:list) cannot call the remove method of list to delete elements, otherwise an exception will be thrown because the Iterator needs to be determined. structure, so there are two ways to delete it. One is to copy a list and remove the elements in the old list by looping through the new list, and the other is to use for(int i; i<count; i++) Loop, so you can delete it through the cursor. Just be careful not to cross the bounds of the array subscript.

習慣沉默

When you are counting eggs, if someone secretly puts eggs in your basket or takes away eggs, it will cause you to count incorrectly. Unless you take away or take in the eggs yourself, you can remember the same principle. This is also true in the program.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!