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方法 

  • 相关阅读:
    jquery实现回车键执行ajax
    php post请求
    题解 P2825 【[HEOI2016/TJOI2016]游戏】
    莫队
    一些关于数学的知识(总结)
    P3232[HNOI2013]游走
    万物生长 / Tribles
    [BZOJ4244]邮戳拉力赛
    P1095 守望者的逃离
    P3953 逛公园
  • 原文地址:https://www.cnblogs.com/caroline4lc/p/4797499.html
Copyright © 2011-2022 走看看