//继承AbstractCollection,实现List接口
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
1、构造函数
//唯一的构造函数,访问权限是protected ,因此只能在子类中构造
protected AbstractList() {
}
2、在List末尾添加一个元素
//UnsupportedOperationException异常:如果列表是可变的,允许添加元素,那么必须重写add(int,E)和remove(int)方法
//ClassCastException异常:如果指定元素的类不允许将该元素添加到此列表
//NullPointerException 异常:如果指定元素为 null 并且此列表不允许使用 null 元素
//IllegalArgumentException - 如果此元素的某些属性不允许将该元素添加到此列表
public boolean add(E e) {
//在列表的末尾添加新元素
add(size(), e);
return true;
}
//在列表的指定位置插入指定元素,将当前处于该位置的元素(如果有的话)和所有后续元素向右移动(在其索引中加 1)。
//可变列表,必须实现该方法
//index - 要在其中插入指定元素处的索引
//element - 要插入的元素
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
3、获取指定位置的元素
//抽象方法
//IndexOutOfBoundsException异常: 如果索引超出范围 (index < 0 || index >= size())
abstract public E get(int index);
4、替换列表中指定位置的元素
//可变列表是重写该方法,否则一直抛UnsupportedOperationException异常
//用指定元素替换列表中指定位置的元素(可选操作)。其中:
//index : 要被替换的元素的索引(旧数据的索引)
//element:要在指定位置存储的元素 (新元素)
// 返回 **以前在指定位置的元素**
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
5、移除列表中指定位置的元素
//将所有的后续元素向左移动(将其索引减 1)。返回从列表中移除的元素。
//index - 要移除的元素的索引
// 返回 以前在指定位置的元素
public E remove(int index) {
throw new UnsupportedOperationException();
}
6、返回此列表中第一次出现的指定元素的索引
public int indexOf(Object o) {
ListIterator<E> it = listIterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return it.previousIndex();
} else {
while (it.hasNext())
if (o.equals(it.next()))
return it.previousIndex();
}
//如果此列表不包含该元素,则返回 -1
return -1;
}