java.util.AbstractSequentialList学习笔记

来源:互联网 发布:日程管理安排软件 编辑:程序博客网 时间:2024/05/12 04:19

概述


java.util.AbstractSequentialList是顺序访问列表的基础抽象类,继承自随机访问基础类java.util.AbstractList。本类基于列表迭代器实现随机访问方法,如:get(int index)set(int index, E element)add(int index, E element)remove(int index)等。当实现一个简单的顺序访问的链表时,仅需要实现`listIteratorsize及其相关方法即可。对于一个只读列表,仅需要实现列表迭代器中的hasNextnexthasPreviouspreviousindex方法即可。对于一个可修改链表,需要实现listIterator的set方法。而对于一个可以改变链表大小的链表,需要实现链表迭代器的remove和add方法。

方法介绍


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

获取链表特定位置的元素。如上所述,链表的随机访问方法基于列表迭代器实现,因此在本方法中,首先生成一个由特定位置开始的列表迭代器,而后直接调用迭代器的next方法返回特定位置的元素。

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

用元素element替代链表特定位置的元素,并返回被替换的值。依然基于列表迭代器实现,其首先生成特定位置开始的列表迭代器,调用next()方法返回当前位置的元素,而后调用ser(e)方法替换指定位置的元素。注意,set方法替换的为列表迭代器紧接上一次调用next()或者previous返回的元素。

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

在链表指定位置中插入一个新元素,基于列表迭代器实现。首先生成特定位置开始的列表迭代器,而后调用迭代器的add(e)方法插入新元素,并做游标的移动(根据插入策略不同,游标移动的策略也不同)。

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

删除链表指定位置的元素,做游标的移动,并将元素返回。其删除的逻辑与set(int, e)基本相同,删除的均为迭代器紧接上一次调用next()或者previous返回的元素。

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

将集合c中所有的元素添加到链表的指定位置中。其实现的基本逻辑也是首先生成特定位置的列表迭代器,而后使用c的迭代器遍历所有元素,依次插入到链表的指定位置中。

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

返回一个基于链表的基础迭代器。目前迭代器已经逐步取代集合框架中的Enumeration接口,其主要有两点不同:

  1. 迭代器允许用户在迭代的过程中,进行删除元素的操作;
  2. 方法名更加直观;
public abstract ListIterator<E> listIterator(int index);

返回一个基于链表元素,由特定位置开始的列表迭代器。

0 0