共同学习Java源代码--数据结构--AbstractSequentialList类

来源:互联网 发布:淘宝书批发 编辑:程序博客网 时间:2024/06/09 16:37

public abstract class AbstractSequentialList<E> extends AbstractList<E> 

这是一个抽象类,继承自AbstractList,是LinkedList的直接父类。

    public E get(int index) {
        try {
            return listIterator(index).next();
        } catch (NoSuchElementException exc) {
            throw new IndexOutOfBoundsException("Index: "+index);
        }
    }

这个方法是获取下一个元素的方法,调用抽象方法listiterator来实现,该方法在子类中有实现。如果捕获异常,则向外继续抛出。

    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);
        }
    }

这个方法是为指定下标赋值的方法。首先获取Listiterator实例e,还是调用那个抽象方法。然后e的指针向后移动一位,并获取当前值。然后赋新值,最后返回当前值。如果捕获异常,则向外继续抛出。

    public void add(int index, E element) {
        try {
            listIterator(index).add(element);
        } catch (NoSuchElementException exc) {
            throw new IndexOutOfBoundsException("Index: "+index);
        }
    }

添加方法,调用listiterator相关方法实现。

    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);
        }
    }

删除方法。

和上面赋值方法类似,都是先获取listiterator实例,然后指针向后移动获取当前值,然后删除当前值,最后返回当前值。一旦捕获异常,则继续向外抛出异常。

    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);
        }
    }

这个是增加参数集合中全部元素的方法。

首先定义一个临时变量modified,代表是否修改了当前集合。然后获取本list的listiterator实例e1,然后获取参数集合的listiterator实例e2。

然后进入while循环,循环条件是e2还有剩余元素。

然后e1进行添加元素。一旦添加,modified临时变量就变成true,代表本集合修改过了。

一旦捕获异常,就继续向外抛出。

    public Iterator<E> iterator() {
        return listIterator();
    }

    public abstract ListIterator<E> listIterator(int index);

这两个方法是获取listiterator方法,底下那个方法是抽象方法,由子类实现。

0 0