jdk-Set接口

Set<E>

类结构

继承接口

  • Collection

实现

接口概述

  • 不包含重复元素
  • 部分实现类可能对包含元素有限制
  • 该接口是Java Collections Framework的成员

接口方法

未声明单独的接口方法,全是Collection接口的方法

AbstractSet

此类提供Set接口的骨架实现,以最大限度地减少实现此接口所需的工作量
通过扩展此类实现集合的过程与通过扩展 AbstractCollection 实现 Collection 的过程相同,只是该类的子类中的所有方法和构造函数都必须遵守Set接口强加的附加约束

此类只实现了equals(),hashCode(),removeAll()三个方法

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

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

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


posted @   carry1899  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示