美文网首页
Java面试遇到的哪些坑-ArrayList循环遍历删除元素

Java面试遇到的哪些坑-ArrayList循环遍历删除元素

作者: 野生Java程序员 | 来源:发表于2020-06-16 07:39 被阅读0次

    © 本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请保留原文链接及作者

    问题引入

    最近公司业务扩张,需要找人,面对如此多的求职责。hr小姐姐可忙不过来,急忙求助与程序猿小哥哥。
    hr: 小哥哥,小哥哥,帮帮筛选一下年龄在30岁以下的候选人
    程序猿:好的,没有问题。
    程序员小哥哥三下五除二就敲完了代码,跑来笑呵呵地向小姐姐邀功。

    public class ArrayListTest{
        public static void main(String[] args) {
            ArrayList<Person> collection = new ArrayList();
            collection.add(new Person("宋青书", 22, "男"));
            collection.add(new Person("小昭", 19, "女"));
            collection.add(new Person("陈友谅", 34, "男"));
            collection.add(new Person("欧阳锋", 75, "男"));
            collection.add(new Person("杨不悔", 25, "女"));
            collection.add(new Person("张三丰", 120, "男"));
            collection.add(new Person("洪七公", 98, "男"));
            collection.add(new Person("张无忌", 34, "男"));
            collection.add(new Person("周芷若", 30, "女"));
            collection.add(new Person("赵敏", 25, "女"));
    
            remove(collection);
    
            for (Person person : collection) {
                System.out.println("name : " + person.getName()+" age : " + person.getAge()+" gender : " + person.getGender());
            }
        }
    
        public static void remove(ArrayList<Person> list) {
            for (int i = 0; i < list.size(); i++) {
                Person person = list.get(i);
                if (person.getAge()>=30) {
                    list.remove(person);
                }
            }
        }
    }
    

    Person 的实体类

    @Data
    public class Person {
        private String name;//姓名
        private Integer age;//年龄
        private String gender;//性别
    
        public Person(String name, Integer age, String gender) {
            this.name = name;
            this.age = age;
            this.gender = gender;
        }
    }
    

    快让我看看有哪些应聘者有面试资格。小姐姐嚷道!
    小哥哥熟练的运行了main方法,瞬间结果就打印出来了。

    候选人名单
    纳尼!欧阳锋和洪七公这两个人什么鬼。小哥哥狠狠的被hr小姐姐鄙视了一番。
    小哥哥哪里服气,于时就采用了第二种方式,采用foreach增强循环来删除遍历应聘者
    public static void remove(ArrayList<Person> list) {
        for (Person person:list) {
             if (person.getAge()>=30) {
                 list.remove(person);
             }
        }
    }
    

    小哥哥麻溜地运行了main方法:


    foreach增强循环运行结果

    小哥哥不甘气馁,采用了迭代器来实现功能。

    public static void remove(ArrayList<Person> list) {
        Iterator iterator=list.iterator();
        while (iterator.hasNext()){
            Person person=(Person) iterator.next();
            if (person.getAge()>=30) {
                list.remove(person);
            }
        }
    }
    
    迭代器运行结果

    下面我们来分析以下这三种方式错误的原因

    1. 采用正向遍历来移除ArrayList中的元素

    要分析产生上述错误现象的原因唯有看看JDK的ArrayList的源码,先看下ArrayList中的remove方法(注意ArrayList中的remove有两个同名方法,只是输入参数不同,这里看的是输入参数是Object的remove方法)是怎么实现的:



    按一般执行路径会走到else路径下最终调用fastRemove(index)方法;



    可以看到会执行System.arraycopy方法,导致删除元素时涉及到数组元素的移动。针对错误写法一,在遍历第二个元素字符串bb时因为符合删除条件,所以将该元素从数组中删除,并且将后一个元素移动(也是字符串bb)至当前位置,导致下一次循环遍历时后一个字符串bb并没有遍历到,所以无法删除。针对这种情况可以倒序删除的方式来避免。

    解决办法如下:

    public static void remove(ArrayList<String> list){
        for(int i=list.size()-1;i>=0;i--){
            Person person = list.get(i);
            if (person.getAge()>=30) {
                list.remove(person);
            }
        }
    }
    

    因为数组倒序遍历时即使发生元素删除也不影响后序元素遍历。

    2. 采用foreach增强循环来删除遍历元素:

    这种for each写法会发现报出著名的并发修改异常Java.util.ConcurrentModificationException
    而错误二、错误三产生的原因却是for each增强for循环写法是对实际的Iterator、hasNext、next方法的简写,问题同样处在上文的fastRemove中,可以看到第一行把modCount变量的值加1,但在ArrayList返回的迭代器(该代码在其父类AbstractList中)

    public Iterator<E> iterator() {  
        return new Itr();  
    }
    

    这里返回的是AbstractList类内部的迭代器实现private class Itr implements Iterator ,看这个类的next方法:

    public E next() {  
        checkForComodification();  
        try {  
            E next = get(cursor);  
            lastRet = cursor++;  
            return next;  
        } catch (IndexOutOfBoundsException e) {  
            checkForComodification();  
            throw new NoSuchElementException();  
        }  
    } 
    

    第一行checkForComodification方法:

    final void checkForComodification() {  
        if (modCount != expectedModCount)  
            throw new ConcurrentModificationException();  
    }  
    

    这里会做迭代器内部修改次数检查,因为你上面的remove(Object)方法把修改了modCount的值,所以才会报出并发修改异常。要避免这种情况的出现,则在使用迭代器迭代时(显式或for each的隐式)不要使用ArrayList的remove,改用Iterator的remove即可。

    3. 采用迭代器来进行删除遍历

    原因和错误二一样,不在赘述。

    解决办法如下:

    public static void remove(ArrayList<Person> list) {
        list.removeIf(person -> person.getAge() >= 30);
    }
    

    在Jdk8里面引入了removeIf方法,方便快捷,代码量还少,推荐使用。

    总结:

    错误原因都是ArrayList集合中remove方法底层的源码中有一个fastRemove(index)方法,然后会有一个modCount++的操作,然后在ArratList内部的迭代器中有一个checkForComodification操作,也就是检查modCount是否改变,如果改变了,就抛出并发修改错误。
    同样的在For each增强for循环中,也是利用了ArrayList自身的Iterator迭代器,也是会出现这样的错误。

    对于一般的for遍历,可能并没有删除要修改的数,可以采用倒序删除的写法改正这个错误。
    对于增强for循环中的遍历,会抛出并发修改异常,使用Iterator自己的remove方法。

    相关文章

      网友评论

          本文标题:Java面试遇到的哪些坑-ArrayList循环遍历删除元素

          本文链接:https://www.haomeiwen.com/subject/oftbtktx.html