zoukankan      html  css  js  c++  java
  • removeAll

    问题:无法移除2个集合中相同元素

    方法:移除所包含的其所有元素。

    在执行removeAll方法时,会先对集合元素进行比较,如果元素相等才执行移除操作,说到这,相信很多人都已经明白是怎么回事了,因为不相等(equals),所以没有执行移除。

    java.util.AbstractCollection<E>

    removeAll

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

     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;
        }
    

    注:if (o.equals(it.next())) !

         上述例子中的实体类没有Override hashCode和equals方法 

  • 相关阅读:
    原型模式(8)
    工厂方法模式(7)
    代理模式(6)
    装饰模式(5)
    策略模式与简单工厂结合(4)
    策略模式(3)
    简单工厂模式(2)
    序(1)
    国际控制报文协议ICMP
    IP 转发分组的流程
  • 原文地址:https://www.cnblogs.com/caroline4lc/p/4797499.html
Copyright © 2011-2022 走看看