Java源码解析 AbstractCollection<E>

位置:  java.util.AbstractCollection<E>
类型:abstract class
用途:
    此类提供了Collection接口最基础的实现,最大限度地减少了实现此接口所需的工作。
    如果实现一个不可修改的collection,程序员只需继承此class并且实现iterator 和size 方法即可。(iterator方法返回的迭代器必须实现hasNext 和next方法)
    如果实现一个可以修改的collection,程序员必须另外重写此class的add 方法(如果不支持需要抛出 UnsupportedOperationException ),而且通过iterator方法返回的迭代器必须另外实现它的remove 方法。
    程序员通常应该提供一个无参的Collection 构造函数,按照Collection接口规范中的建议
    文档详细的描述了此类中每一个非抽象方法的具体实现。集合实现中,如果有更有效率的实现,那么这些实现的方法都是可以被重写的
    此类是Java Collection Framework中的一员

参数:
父类:Object
子类:AbstractList,AbstractQueue,AbstractSet,ArrayDeque,ConcurrentLinkedDeque
接口:Iterable<E>,Collection<E>
public abstract class AbstractCollection<E> implements Collection<E> {  
     /**
     * 唯一构造函数(供子类构造调用)
     */
    protected AbstractCollection() {
    }
     /**
     * 返回一个迭代器包含此集合中的元素
     */
    public abstract Iterator<E> iterator();
    /**
     * 返回长度
     */
    public abstract int size();
     /**
     * 返回true 当size()==0
     */
    public boolean isEmpty() {
        return size() == 0;
    }  
         /**
     * 这个实现是遍历了此集合中的所有的元素,check 每个元素与制定元素的相等性
     */
    public boolean contains(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return true;
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return true;
        }
        return false;
    }  
     /**
     * {@inheritDoc}
     *
  
     *这个实现返回一个包含所有元素的数组由此Collection的迭代器返回,相同的顺序,连续存储在数组中,起始于0.
     *返回数组的长度和迭代器返回的元素的数量相等,即使此Collection的长度在迭代过程中发生变化,因为可能会发生,如果              collection允许迭代期间并发发生。
     *size()方法的调用只是一个优化的提示;即使迭代器返回不同数量的元素也会返回正确的结果
     * <p>这个方法等效于:
     *
     *  <pre> {@code
     * List<E> list = new ArrayList<E>(size());
     * for (E e : this)
     *     list.add(e);
     * return list.toArray();
     * }</pre>
     */
    public Object[] toArray() {
        // Estimate size of array; be prepared to see more or fewer elements
        Object[] r = new Object[size()];
        Iterator<E> it = iterator();
        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) // fewer elements than expected
                return Arrays.copyOf(r, i);//如果迭代器中的元素比size声明的数组小,就设置数组的长度为当前长度
            r[i] = it.next();
        }
        return it.hasNext() ? finishToArray(r, it) : r;
    }
    /**
     * {@inheritDoc}
     *
     *这个实现返回一个包含所有元素的数组由此Collection的迭代器返回,相同的顺序,连续存储在数组中,起始于0.
     *如果迭代器中的元素数量大于指定数组长度,会新分配一个数组来存储这些元素,即使此Collection的长度在迭代过程中发生变化,因为可能会发生,如果collection允许迭代期间并发发生。
     *size()方法的调用只是一个优化的提示;即使迭代器返回不同数量的元素也会返回正确的结果
     *
     *
     *
     *
     * <p>这个方法等效于:
     *
     *  <pre> {@code
     * List<E> list = new ArrayList<E>(size());
     * for (E e : this)
     *     list.add(e);
     * return list.toArray(a);
     * }</pre>
     *
     * @throws ArrayStoreException  {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public <T> T[] toArray(T[] a) {
        // Estimate size of array; be prepared to see more or fewer elements
        int size = size();
        T[] r = a.length >= size ? a :
                  (T[])java.lang.reflect.Array
                  .newInstance(a.getClass().getComponentType(), size);//判断此集合的size 和指定的a数组长度,如果a不适合就重新实例化一个数组
        Iterator<E> it = iterator();
        for (int i = 0; i < r.length; i++) {
            if (! it.hasNext()) { // fewer elements than expected
                if (a == r) {
                    r[i] = null// null-terminate
                } else if (a.length < i) {
                    return Arrays.copyOf(r, i);
                } else {
                    System.arraycopy(r, 0, a, 0, i);
                    if (a.length > i) {
                        a[i] = null;
                    }
                }
                return a;
            }
            r[i] = (T)it.next();
        }
        // more elements than expected 有更多元素比size更多
        return it.hasNext() ? finishToArray(r, it) : r;
    }
    /**
     
     * 数组可以分配的最大值。
     * 一些虚拟机在数组中保留一些头文字
     * 企图声明更大的数组会返回OutofMemoryError:请求的数组长度超过了VM的限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    /**
     *toArray 方法迭代器返回的元素个数超过了size(),此方法用来重新分配数组来完成这些元素的添加
     *
     * @param r 此数组, 已经存满的数组
     * @param it 此collection中正在迭代的迭代器
     * @return 返回一个数组,包含之前数组的元素,并且增加更多iterator中的元素,并且修改了size
     */
    private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
        int i = r.length;
        while (it.hasNext()) {
            int cap = r.length;
            if (i == cap) {
                int newCap = cap + (cap >> 1) + 1;
                // overflow-conscious code
                if (newCap - MAX_ARRAY_SIZE > 0)
                    newCap = hugeCapacity(cap + 1);//判断分配的数组空间是否超越临界值
                r = Arrays.copyOf(r, newCap);
            }
            r[i++] = (T)it.next();
        }
        // trim if overallocated
        return (i == r.length) ? r : Arrays.copyOf(r, i);//当前数组长度和元素个数是否相同,不同的话,就调整下数组
    }
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError
                ("Required array size too large");
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    // Modification Operations
    /**
     * {@inheritDoc}
     *
     * <p>这个实现没有具体实现只是会抛不支持操作的异常
     * <tt>UnsupportedOperationException</tt>.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IllegalStateException         {@inheritDoc}
     */
    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }
    /**
     * {@inheritDoc}
     *
     *这个实现迭代此collection找寻指定元素,如果找到了这个元素,就从此collection中移除这个元素,使用迭代器的remove方法,并返回true
     *
     *
     *此实现会抛出不支持的操作异常,如果此集合中的迭代器没有实现remove方法,但是此collection中包含指定的对象
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     */
    public boolean remove(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {//o==null 并且迭代器中可以有null 那么 return true
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) { //equals()
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }
    // 批量操作
    /**
     * {@inheritDoc}
     *
     *此实现迭代所有指定collection,检查所有的元素释放包含在此collection中,如果所有的元素都包含在内就返回true,否则返回false
     *
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @see #contains(Object)
     */
    public boolean containsAll(Collection<?> c) {
        for (Object e : c)
            if (!contains(e))
                return false;
        return true;
    }
    /**
     * {@inheritDoc}
     *
     *此实现迭代所有指定的collection,循环迭代器中的每一个object并添加
     *
     *需要注意的是此实现会排出不支持操作异常,除非add被重写(假设指定的collection是非空)
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     * @throws IllegalArgumentException      {@inheritDoc}
     * @throws IllegalStateException         {@inheritDoc}
     *
     * @see #add(Object)
     */
    public boolean addAll(Collection<? extends E> c) {
        boolean modified = false;
        for (E e : c)
            if (add(e))
                modified = true;
        return modified;
    }
    /**
     * {@inheritDoc}
     * 此实现迭代此collection,迭代器中返回的每一个元素都轮流检查是否包含在指定的collection中,如果包含其中,那就调用此collection中迭代器的remove方法移除掉
     * 
     * 需要注意的是,此实现会抛不支持操作的异常。如果此集合返回的迭代器没有实现remove方法而此collection中包含一个或多个元素在指定的collection中
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     *
     * @see #remove(Object)
     * @see #contains(Object)
     */
    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;
    }
    /**
     * {@inheritDoc}
     *
     * 此实现迭代此collection,迭代器中返回的每一个元素都轮流检查是否包含在指定的collection中,如果不包含其中,就调用此collection的迭代器的remove方法移除掉
     *
     * 需要注意的是,此实现会抛不支持操作的异常。如果此collection返回的迭代器没有实现remove方法而此collection中一个或多个元素不在在指定的collection中
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     *
     * @see #remove(Object)
     * @see #contains(Object)
     */
    public boolean retainAll(Collection<?> c) {
        boolean modified = false;
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            if (!c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }
    /**
     * {@inheritDoc}
     *
     * 此实现迭代此collection,移除每一个元素使用迭代器的remove操作。大多数实现会选择重写这个方式为了效率
     * 
     * 需要注意的是此实现会抛出不支持操作的异常,如果此collection的返回的迭代器没有实现remove方法,但是此collection非空
     * 
     * @throws UnsupportedOperationException {@inheritDoc}
     */
    public void clear() {
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            it.next();
            it.remove();
        }
    }
    //  字符串转换
    /**
     * 此collection用字符串形态展示。字符串展现由此collection返回的迭代器中的按照顺序的list,方括号括起来,“[]”.相邻的元素使用“, ”分割(一个逗号和一个空格),元素按照String。valueOf(Object)转换成字符串
     * @return 返回此collection的字符串形态
     */
    public String toString() {
        Iterator<E> it = iterator();
        if (! it.hasNext())
            return "[]";
        StringBuilder sb = new StringBuilder();//使用的是StringBuilder
        sb.append('[');
        for (;;) {
            E e = it.next();
            sb.append(e == this ? "(this Collection)" : e);
            if (! it.hasNext())
                return sb.append(']').toString();
            sb.append(',').append(' ');
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mingjie1212

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值