源码看JAVA【十九】AbstractSet

1、AbstractSet比较简单,无序集合的抽象,继承了AbstractCollection

2、equals判断两个集合值是否全部包含,最后判断集合的大小,都一致说明两个集合内容一致。

     public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Set))
            return false;
        Collection<?> c = (Collection<?>) o;
        if (c.size() != size())
            return false;
        try {
            return containsAll(c);
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

3、hashCode:集合所有的hashCode值相加,两个集合的hashCode值一致的情况就非常多了。

     public int hashCode() {
        int h = 0;
        Iterator<E> i = iterator();
        while (i.hasNext()) {
            E obj = i.next();
            if (obj != null)
                h += obj.hashCode();
        }
        return h;
    }

4、removeAll:遍历集合,存在一致的则一个一个删除。

     public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;

        if (size() > c.size()) {
            for (Iterator<?> i = c.iterator(); i.hasNext(); )
                modified |= remove(i.next());
        } else {
            for (Iterator<?> i = iterator(); i.hasNext(); ) {
                if (c.contains(i.next())) {
                    i.remove();
                    modified = true;
                }
            }
        }
        return modified;
    }

   转载规则


《源码看JAVA【十九】AbstractSet》 Euler 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录