AbstractSequentialList源码分析

该类与AbstractList类是另外一套抽象类,前者是在迭代器的基础上实现的get、set、add和remove方法,后者则是随机访问基础上实现这些方法。


源码分析(JDK1.8)

//构造方法
protected AbstractSequentialList() {
}

//根据索引获取元素(通过迭代器寻找元素)
public E get(int index) {
  try {
    return listIterator(index).next();
  } catch (NoSuchElementException exc) {
    throw new IndexOutOfBoundsException("Index: "+index);
  }
}

//根据索引更新元素(通过迭代器寻找元素)
public E set(int index, E element) {
  try {
    ListIterator<E> e = listIterator(index);
    E oldVal = e.next();
    e.set(element);
    return oldVal;
  } catch (NoSuchElementException exc) {
    throw new IndexOutOfBoundsException("Index: "+index);
  }
}

//根据索引添加元素(通过迭代器寻找元素)
public void add(int index, E element) {
  try {
    listIterator(index).add(element);
  } catch (NoSuchElementException exc) {
    throw new IndexOutOfBoundsException("Index: "+index);
  }
}

//根据索引删除迭代器(通过迭代器寻找元素)
public E remove(int index) {
  try {
    ListIterator<E> e = listIterator(index);
    E outCast = e.next();
    e.remove();
    return outCast;
  } catch (NoSuchElementException exc) {
    throw new IndexOutOfBoundsException("Index: "+index);
  }
}

//在索引位置后添加其他容器数据
public boolean addAll(int index, Collection<? extends E> c) {
  try {
    boolean modified = false;
    ListIterator<E> e1 = listIterator(index);
    Iterator<? extends E> e2 = c.iterator();
    while (e2.hasNext()) {
      e1.add(e2.next());
      modified = true;
    }
    return modified;
  } catch (NoSuchElementException exc) {
    throw new IndexOutOfBoundsException("Index: "+index);
  }
}

//获取迭代器
public Iterator<E> iterator() {
  return listIterator();
}

//抽象类,获取next为index的迭代器
public abstract ListIterator<E> listIterator(int index);


总结:

通过代码可以知道,几乎所有方法都依靠 listIterator(int index)抽象方法 来实现,功能都是依靠迭代器,不支持快速随机访问,及不支持RandomAccess。

posted @ 2020-06-08 12:49  卑斯的卑微  阅读(153)  评论(0编辑  收藏  举报