JDK1.8 AbstractCollection

1、AbstractCollection抽象类描叙

AbstractCollection这个抽象类是开发者基于Collection接口的基础上实现了很多功能。有时候具体的实现类并不想实现接口的所有方法,而如果继承AbstractCollection这个抽象类,只需要实现其抽象方法就行,这也是集合元素所必须的,其他的方法就可以选择性的进行重写。

2、主机构图

抽象类AbstractCollection实现了Collection接口

3、源码分析
public abstract class AbstractCollection<E> implements Collection<E> {
  /**
   * 用于子类构造函数调用,通常是隐式的。
   *
   */
  protected AbstractCollection() {
  }

  // Query Operations

  /**
   * 返回此集合中包含的元素的迭代器。
   *
   */
  public abstract Iterator<E> iterator();

  //获取大小
  public abstract int size();

  //判空
  public boolean isEmpty() {
    return size() == 0;
  }

  /**
   *
   * 判断集合是否包含指定元素 包含返回true否则返回false
   * @throws ClassCastException   {@inheritDoc   类型转换异常
   * @throws NullPointerException {@inheritDoc}  空指针异常
   */
  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}
   *
   * 如果迭代器返回的元素数量太大而不适合指定的数组,
   * 那么元素将在新分配的数组中返回,其长度等于迭代器返回的元素数,
   * 即使此集合的大小发生更改 在迭代期间
   *
   * <p>This method is equivalent to:
   *
   *  <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);
      r[i] = it.next();
    }
    return it.hasNext() ? finishToArray(r, it) : r;
  }

  /**
   * {@inheritDoc}
   *
   * 如果迭代器返回的元素数量太大而不适合指定的数组,
   * 那么元素将在新分配的数组中返回,其长度等于迭代器返回的元素数,
   * 即使此集合的大小发生更改 在迭代期间
   *
   * <p>This method is equivalent to:
   *
   *  <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}
   */
  @SuppressWarnings("unchecked")
  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);
    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
    return it.hasNext() ? finishToArray(r, it) : r;
  }

  /**
   * 准许数组的最大值
   * 由于vm原因导致内存问题
   * OutOfMemoryError: Requested array size exceeds VM limit
   */
  private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

  /**
   *    在迭代器时重新分配toArray中使用的数组返回比预期更多的元素,并完成填充
   * 迭代器。
   *
   * @param r 以前存储的元素的数组
   * @param it 这个集合的正在进行的迭代器
   * @return 包含给定数组中的元素,以及迭代器返回的任何其他元素的数组,按大小进行裁剪
   *
   */
  @SuppressWarnings("unchecked")
  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}
   *
   * 该方法当前类没有具体实现,需自行实现。
   * <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}
   *
   * 移除集合中的元素
   *
   * @throws UnsupportedOperationException {@inheritDoc}
   * @throws ClassCastException            {@inheritDoc}
   * @throws NullPointerException          {@inheritDoc}
   */
  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;
  }


  // Bulk Operations

  /**
   * {@inheritDoc}
   *
   * 指定集合是否包含在当前集合中 包含返回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}
   *
   * 将指定集合添加到当前集合中
   *
   * @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}
   *
   * 移除指定集合中的元素
   *
   * @throws UnsupportedOperationException {@inheritDoc}
   * @throws ClassCastException            {@inheritDoc}
   * @throws NullPointerException          {@inheritDoc}
   *
   * @see #remove(Object)
   * @see #contains(Object)
   */
  public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<?> it = iterator();
    while (it.hasNext()) {
      if (c.contains(it.next())) {
        it.remove();
        modified = true;
      }
    }
    return modified;
  }

  /**
   * {@inheritDoc}
   *
   * 取两集合的交集
   *
   * @throws UnsupportedOperationException {@inheritDoc}
   * @throws ClassCastException            {@inheritDoc}
   * @throws NullPointerException          {@inheritDoc}
   *
   * @see #remove(Object)
   * @see #contains(Object)
   */
  public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<E> it = iterator();
    while (it.hasNext()) {
      if (!c.contains(it.next())) {
        it.remove();
        modified = true;
      }
    }
    return modified;
  }

  /**
   * {@inheritDoc}
   *
   * 清除集合
   *
   * @throws UnsupportedOperationException {@inheritDoc}
   */
  public void clear() {
    Iterator<E> it = iterator();
    while (it.hasNext()) {
      it.next();
      it.remove();
    }
  }


  //  String conversion

  /**
   *
   * 将集合字符化
   * 
   * @return 字符串
   */
  public String toString() {
    Iterator<E> it = iterator();
    if (! it.hasNext())
      return "[]";

    StringBuilder sb = new 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(' ');
    }
  }

}

4、方法结构图

JDK1.8 AbstractCollection