源码分析之List(一)List & AbstractList

   ListCollection三大直接子接口之一,其中的数据可以通过位置检索,用户可以在指定位置插入数据。List的数据可以为空,可以重复。

List

  Collection主要提供一些通用的方法,而List则针对线性表的结构,提供了对位置以及子表的操作。特有方法如下:

public interface List<E> extends Collection<E> {
    //在指定位置,将指定的集合插入到当前的集合中
  boolean addAll(int index, Collection<? extends E> c);
  //这是一个默认实现的方法,会通过Iterator的方式对每个元素进行指定的操作
  default void replaceAll(UnaryOperator<E> operator) {
      Objects.requireNonNull(operator);
      final ListIterator<E> li = this.listIterator();
      while (li.hasNext()) {
          li.set(operator.apply(li.next()));
      }
  }
  //排序,依据指定的规则对当前集合进行排序,可以看到,排序是通过Arrays这个工具类完成的。
  default void sort(Comparator<? super E> c) {
      Object[] a = this.toArray();
      Arrays.sort(a, (Comparator) c);
      ListIterator<E> i = this.listIterator();
      for (Object e : a) {
          i.next();
          i.set((E) e);
      }
  }
  //获取指定位置的元素
  E get(int index);
  //修改指定位置元素的值
  E set(int index, E element);
  //将指定元素添加到指定的位置
  void add(int index, E element);
  //将指定位置的元素移除
  E remove(int index);
  //返回一个元素在集合中首次出现的位置
  int indexOf(Object o);
  //返回一个元素在集合中最后一次出现的位置
  int lastIndexOf(Object o);
  //ListIterator继承于Iterator,主要增加了向前遍历的功能
  ListIterator<E> listIterator();
  //从指定位置开始,返回一个ListIterator
  ListIterator<E> listIterator(int index);
  //返回一个子集合[fromIndex, toIndex),非结构性的修改返回值会反映到原表,反之亦然。如果原表进行了结构修改,则返回的子列表可能发生不可预料的事情
  List<E> subList(int fromIndex, int toIndex);
}

AbstractList

  提供了一些方法的实现,不能被实例化。

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    /**
     * Sole constructor.  (For invocation by subclass constructors, typically
     * implicit.)
     */
    protected AbstractList() {
    } 
}
原文地址:https://www.cnblogs.com/ryjJava/p/14313528.html