本章关于抽象列列表做介绍
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> //继承了抽象集合并且实现List接口
抽象方法
abstract public E get(int index); 返回指定索引的元素
这里写代码片
具体方法
public boolean add(E e) { //添加一个元素
add(size(), e);
return true;
}
public E set(int index, E element) { //替换指定位置元素,总是抛出不支持该操作异常
throw new UnsupportedOperationException();
}
public void add(int index, E element) { //在指定位置插入元素,总是抛出不支持该操作异常
throw new UnsupportedOperationException();
}
public E remove(int index) { //删除指定位置元素,总是抛出不支持该操作异常
throw new UnsupportedOperationException();
}
public int indexOf(Object o) { //返回o的索引,通过ListIterator遍历集合
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())) //当运行it.next之后it已经向后走了,所以对应的索引是it 的前一个索引
return it.previousIndex();
}
return -1;
}
//iterator往前遍历,listIterator在Iterator的基础上又增加了previous方法(因为是线性,所以可以往前遍历
public int lastIndexOf(Object o) {
ListIterator<E> it = listIterator(size()); //初始化是多少则ListIterator对象的开始索引就在哪儿
if (o==null) {
while (it.hasPrevious())
if (it.previous()==null)
return it.nextIndex();
} else {
while (it.hasPrevious())
if (o.equals(it.previous()))
return it.nextIndex();
}
return -1;
}
//清空列表
public void clear() {
removeRange(0, size());
}
//从index开始插入集合C中的元素
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
boolean modified = false;
for (E e : c) {
add(index++, e);
modified = true;
}
return modified;
}
//两个集合相同必须每个元素都相同
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator e2 = ((List) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
//删除范围内的元素
protected void removeRange(int fromIndex, int toIndex) {
ListIterator<E> it = listIterator(fromIndex);
for (int i=0, n=toIndex-fromIndex; i<n; i++) {
it.next();
it.remove();
}
}
域
protected transient int modCount = 0; 集合被修改的次数