Java集合中remove()方法解析

发布时间:2023-07-07 17:30

public class removeText {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        String s1 = new String("hello");
        c.add(s1);
        String s2 = new String ("hello");

        c.remove(s2);
        System.out.println(c.size());
    }
}

问:最终的输出结果是什么?

答案:0

我们向集合中加入的是s1,remove的是s2,为什么还能删除成功呢?

原因很简单,remove()方法和contains()方法一样,底层都实现了equals()方法

s1.equals(s1)是true,所以答案是true。

另外!还有更重要的!!!!!!

删除元素之后,相当于集合结构发生变化,如果使用迭代器的时候,记得重新获取

public class removeText {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        String s1 = new String("hello");
        c.add(s1);
        String s2 = new String ("abc");
        c.add(s2);

        Iterator it = c.iterator();
        while(it.hasNext()){
            Object o = it.next();
            c.remove(o);
            System.out.println(o);
        }

    }
}

如上图代码所示,我们在使用迭代器的时候,清楚了集合中某个对象,此种的结果就会出现异常:Java集合中remove()方法解析_第1张图片

原因:通过此种删除方式并没有通知迭代器,导致迭代器快照和原状态集合不同,出现异常。

     迭代器就像是一个照片,而集合就像是现实。我们现实改变了,但是照片不可能改变,此时就出现了不匹配的异常,如果消除异常,就必须重现拍照,和现实相同,就是再重现获取迭代器。

而且在迭代过程中,一定要使用迭代器Iterator的remove方法,而不是集合的

 

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号