List是有序的 collection(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。
AbstractSequentialList提供了 List 接口的骨干实现,从而最大限度地减少了实现受“连续访问”数据存储(如链接列表)支持的此接口所需的工作。
//List接口,继承于Collection接口
public interface List<E> extends Collection<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean addAll(int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
E get(int index);//获取第index个元素
E set(int index, E element);//设置第index个元素的值为element
void add(int index, E element);//在第index个位置前插入元素element
E remove(int index);//删除第index个元素
int indexOf(Object o);//从头定位值为o的元素
int lastIndexOf(Object o);//从后定位值为o的元素
ListIterator<E> listIterator();//返回系列表迭代器
ListIterator<E> listIterator(int index);//从第index开始的系列表迭代器,该迭代器介绍如下
List<E> subList(int fromIndex, int toIndex);//返回fromindex开始到toIndex结束的视图
}
//系列表迭代器,提供了更多操作
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();//是否有下一个元素
E next();//下一个元素
boolean hasPrevious();//是否有前一个元素
E previous();//前一个元素
int nextIndex();//下一个索引
int previousIndex();//前一个索引
void remove();//删除元素
void set(E e);//设置元素的值
void add(E e);//添加元素
}
//继承了AbstractList接口,该类实现了一种类似链表的结构,不支持随机访问
public abstract class AbstractSequentialList<E> extends AbstractList<E> {
protected AbstractSequentialList() {//提供一个空的默认构造函数
}
//获取第index个元素
public E get(int index) {
try {
return listIterator(index).next();//通过迭代器实现
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
//修改第index个位置的值为element
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);
}
}
//在第index个位置添加值element
public void add(int index, E element) {
try {
listIterator(index).add(element);
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+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();
}
//提供双向迭代器
public abstract ListIterator<E> listIterator(int index);
}