JDK源码-Collection-remove()以及removeAll()

来源:互联网 发布:论文检测软件下载 编辑:程序博客网 时间:2024/06/06 20:43

remove()


再让我们来看一个处理与contains非常相似的方法,那就是remove()方法。源码如下:

public boolean remove(Object o) {        Iterator<E> it = iterator();        if (o==null) {            while (it.hasNext()) {                if (it.next()==null) {                    it.remove();                    return true;                }            }        } else {            while (it.hasNext()) {                if (o.equals(it.next())) {                    it.remove();                    return true;                }            }        }        return false;}

这块处理其实都是采用的迭代,Collection继承了Iterator,当然还有很多类继承了Collection,并对他的方法进行了重写。我们先了解父类的方法之后,后面我们会对个各子类中方法进行介绍。

removeAll()

直接看源码:

public boolean removeAll(Collection<?> c) {        Objects.requireNonNull(c);        boolean modified = false;        Iterator<?> it = iterator();        while (it.hasNext()) {            if (c.contains(it.next())) {                it.remove();                modified = true;            }        }        return modified;    }

和containsAll原理一样,通过迭代来的,只要对象包含在collection中就remove掉这个对象。之后就返回值定义成true。

细心的人会发现,remove这个方法全部用的迭代(Iterator),

1.为什么不用for循环呢?

因为如果collection有下标,例如list(i),你一边remove,list的下标也是会发生变化的,所以,remove不用for会出错的。

2.为什么不用foreach?

没有为什么,人家就是选择了这个而已,别想太多。foreach循环就是用的iterator,foreach循环编译后还是被转成了iterator。




原创粉丝点击