public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
拥有抽象类AbstractCollection的功能AbstractCollection源码
//添加某个元素
public boolean add(E e) {
add(size(), e);//在集合的末尾添加
return true;
}
//提供一个待实现的方法,子类必须实现;主要考虑最终的实现类可能未线程安全类和线程非安全类。这里交给子类实现的目的是定义算法结构,实现交给子类完成;非常标准的模板方法模式
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
//获取某个元素(给定位置)--抽象方法,子类实现
abstract public E get(int index);
//跟add一致思路
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
//跟add一致思路
public E remove(int index) {
throw new UnsupportedOperationException();
}
//
public int indexOf(Object o) {
ListIterator<E> it = listIterator();//获取list迭代器
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();
}
return -1;
}
//
public int lastIndexOf(Object o) {
ListIterator<E> it = listIterator(size());
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;
}
下面的待续。。。。
=========================================================================================
ListIterator实现
--实现Itr类
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
cursor = index;
}
public boolean hasPrevious() {
return cursor != 0;
}
public E previous() {
checkForComodification();
try {
int i = cursor - 1;
E previous = get(i);
lastRet = cursor = i;
return previous;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor-1;
}
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.set(lastRet, e);
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
checkForComodification();
try {
int i = cursor;
AbstractList.this.add(i, e);
lastRet = -1;
cursor = i + 1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}