public abstract class AbstractSequentialList<E> extends AbstractList<E> {//继承AbstractList JDK1.7 java.util
protected AbstractSequentialList() {//构造器protected
}
public E get(int index) {//返回此列表中指定位置上的元素
try {
return listIterator(index).next();//直接从此处开始迭代然后获取返回
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
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);
}
}
public void add(int index, E element) {//在此列表中的指定位置上插入指定的元素
try {
listIterator(index).add(element);//直接迭代插入元素
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("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) {//在此列表中指定的位置上插入指定 collection 中的所有元素
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);//双向迭代器
}
Java集合之AbstractSequentialList
最新推荐文章于 2023-03-18 14:54:41 发布