Java集合之AbstractSet

来源:互联网 发布:如何安装网络驱动程序 编辑:程序博客网 时间:2024/06/06 14:20
//此类提供 Set 接口的骨干实现,从而最大限度地减少了实现此接口所需的工作      JDK1.7   java.utilpublic abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {//构造方法    protected AbstractSet() {    }      //比较指定对象与此 set的相等性    public boolean equals(Object o) {        if (o == this)            return true;//引用相等则必然相等        if (!(o instanceof Set))            return false;//必须是set或其子类        Collection c = (Collection) o;        if (c.size() != size())            return false;//长度不等则false        try {            return containsAll(c);//比较        } catch (ClassCastException unused)   {            return false;        } catch (NullPointerException unused) {            return false;        }    }    //返回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;    }        //从此 set中移除包含在指定 collection 中的所有元素    public boolean removeAll(Collection<?> c) {        boolean modified = false;        if (size() > c.size()) {            for (Iterator<?> i = c.iterator(); i.hasNext(); )//如果原集合中元素较多,则迭代c                modified |= remove(i.next());        } else {            for (Iterator<?> i = iterator(); i.hasNext(); ) {//如果c中元素较多,则迭代c                if (c.contains(i.next())) {                    i.remove();                    modified = true;                }            }        }        return modified;    }}

0 0
原创粉丝点击