AbstractSequentialList说明

来源:互联网 发布:人工智能综述 编辑:程序博客网 时间:2024/06/05 03:28

AbstractSequentialList也是一个抽象类,它的声明如下:

public abstract class AbstractSequentialList extends AbstractList
有关AbstractList:http://blog.csdn.net/treeroot/archive/2004/09/14/104743.aspx

这个类的代码比较简单

public Object get(int index) {
  ListIterator e = listIterator(index);
  try {
    return(e.next());
  } catch(NoSuchElementException exc) {
    throw(new IndexOutOfBoundsException("Index: "+index));
  }
}

public Object set(int index, Object element) {
  ListIterator e = listIterator(index);
  try {
    Object oldVal = e.next();
    e.set(element);
    return oldVal;
  } catch(NoSuchElementException exc) {
    throw(new IndexOutOfBoundsException("Index: "+index));
  }
}

public void add(int index, Object element) {
  ListIterator e = listIterator(index);
  e.add(element);
}

public Object remove(int index) {
  ListIterator e = listIterator(index);
  Object outCast;
  try {
    outCast = e.next();
  } catch(NoSuchElementException exc) {
    throw(new IndexOutOfBoundsException("Index: "+index));
  }
  e.remove();
  return(outCast);
}

public boolean addAll(int index, Collection c) {
  boolean modified = false;
  ListIterator e1 = listIterator(index);
  Iterator e2 = c.iterator();
  while (e2.hasNext()) {
    e1.add(e2.next());
    modified = true;
  }
  return modified;
}

public Iterator iterator() {
  return listIterator();
}

public abstract ListIterator listIterator(int index);

注意到所有的方法都使用迭代器,明显设计的不好,没有做到fast-fail,应该是先简单是否越界
不过子类都会重写这些方法。由于这些代码都比较简单,前面的一些类中也有类似的情况,这里只是
提供一个通用的实现,这里列出来只是为了方便分析LinkedList,因为LinkedList是它的子类。

原创粉丝点击