List集合框架解析—基于JDK1.8

ArrayList

ArrayList数据结构

ArrayList本质上是一个动态数组,该集合类就是围绕动态数组特性(可变长数组)进行设计。
下面通过阅读源码分析构造方法和常用的API,解释ArrayList为什么是一个动态数组。
构造函数和成员变量:

// 数组默认容量
private static final int DEFAULT_CAPACITY = 10;
// 空数组,用户指定集合容量初始值为0时使用
private static final Object[] EMPTY_ELEMENTDATA = {};
// 默认数组,使用默认构造函数创建集合时使用,将值赋值给elementData
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 容器,真正存储集合元素的数组
transient Object[] elementData;
// 记录elementData中实际存储元素的个数,每次新增或删除元素,都要修改该值
private int size;
/**
 * 默认构造函数,生成一个空数组
 */
public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
/**
 * 生成具有指定容量initialCapacity的数组
 */
public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
/**
 * 生成具有指定Collection集合元素的数组
 */
public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

常用API:由于ArrayList的API实在太多,这里就不一一列举了,笔者就日常工作最常用的操作:增、删、改、查,分析ArrayList是如何实现动态数组特性。

/**
 * 查找元素:获取下标为index的数组元素
 */
public E get(int index) {
		// 判断index是否越界
        rangeCheck(index);

        return elementData(index);
    }
/**
 * 修改元素:修改下标为index的数组元素,并返回修改前下标为index的数组元素
 */
public E set(int index, E element) {
		// 判断index是否越界
        rangeCheck(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
/**
 * 新增元素:在数组末尾新增元素
 */
public boolean add(E e) {
		// 确定数组内存储元素的个数,若数组已满,则扩容数组
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
/**
 * 在指定下标处新增元素,将原下标为index数组元素及其后继元素依次向后移一位
 */
public void add(int index, E element) {
		// 判断index是否越界
        rangeCheckForAdd(index);
		// 确定数组内存储元素的个数,若数组已满,则扩容数组
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // 将原下标为index数组元素及其后继元素依次向后移一位
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        // 将增加元素存储到数组下标index处                 
        elementData[index] = element;
        size++;
    }
/**
 * 删除下标为index数组元素
 */
public E remove(int index) {
		// 判断index是否越界
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
        	// 将下标为index+1数组元素及其后继元素依次向前移一位,这样下标为index的数组元素就被清空了
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        // 由于上一步操作,elementData[--size]和elementData[size-1]存储的元素相同,
        //为释放多余的内存空间,将elementData[--size]元素赋值为null,利用GC机制,回收elementData[--size]指向的对象。
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }
/**
 * 删除数组中存储对象为o的数组元素
 */
public boolean remove(Object o) {
        if (o == null) {
        	// 遍历数组,找到存储对象为o的数组元素的下标index,循环删除下标为index的数组元素
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                	// 删除下标为index数组元素
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
/**
 * 删除下标为index数组元素
 */
private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

通过阅读源码,我们发现:ArrayList集合元素存储在成员变量Object[] elementData中,对ArrayList集合元素的操作,就是对数组elementData的操作。get、set方法只是对指定下标数组元素进行查找、修改,而add、remove方法则会产生数组扩容、复制等操作。
数组如何复制?
通过调用System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 实现,该方法会将源数组从指定位置复制到目标数组的指定位置,由于该方法被native修饰,是一种本地方法,笔者能力有限,对其所知甚少,大家可以去相关博客,论坛了解该方法。
数组何时会扩容?如何实现扩容?
调用新增元素方法add(E e)、add(int index, E element)、addAll(int index, Collection<? extends E> c)等方法时会调用ensureCapacityInternal(size + 1)方法,该方法就是确定数组内存储元素的个数,若新增元素会造成数组溢出,则扩容数组。
阅读ensureCapacityInternal方法源码

/**
 * 确定数组内存储元素的个数
 */
private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
/**
 * 明确若新增元素,目前数组是否能容纳新增的元素,若不能容纳,则调用grow方法扩容数组
 */
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
/**
 * 确定当前数组所需容量
 */
private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
/**
 * 扩容数组
 */
private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        // 将数组扩容到原来的3/2
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        // 确定数组扩容容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // 复制数组
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
/**
 * 集合内数组允许的最大容量
 */
private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

首先,调用calculateCapacity方法确定当前数组内元素个数,接下来ensureExplicitCapacity方法调用calculateCapacity方法的返回值,判断目前数组是否能容纳新增的元素,若不能容纳,则调用grow方法扩容数组,grow方法首先设置新容量newCapacity为原来数组容量的1/2,比较方法参数minCapacity,这个参数表示扩容的数组需存储minCapacity个元素,若大于minCapacity,则扩容到原来数组容量的1/2;若小于minCapacity,比较minCapacity和MAX_ARRAY_SIZE(这个值已经很大了,大家可以查看源代码,了解这个值)大小, 如若还不满足,扩容到Integer.MAX_VALUE。之后,即使在添加元素,数组也不会扩容。
再细心一些,会发现add、remove方法里都对成员变量modCount进行了修改,该变量是确保使用迭代器迭代集合期间,不允许对集合元素进行新增、删除等改变数组元素长度的操作。阅读迭代器部分,看看迭代器是如何利用modCount成员变量保证迭代元素的准确性的。

ArrayList迭代器

ArrayList内部实现了3种迭代器
名词讲解:光标:表示在迭代器遍历集合时,当前元素的索引。例如从下标为0的元素开始遍历,光标为0。

  1. 实现了Iterator接口的迭代器。该迭代器提供了最基本的迭代功能。
private class Itr implements Iterator<E> {
		 /**
		 * 迭代器光标所在位置索引
		 * 是否具有下一个元素,迭代取值等操作,都是根据该值确定数组元素位置
		 */
        int cursor;
        // 光标所在位置的索引       
        int lastRet = -1; 
        int expectedModCount = modCount;

        Itr() {}
		/**
		 * 判断光标后是否有下一个元素	
		 */
        public boolean hasNext() {
            return cursor != size;
        }
		/**
		 * 返回下一个数组元素	
		 */
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            // 光标向后移一位
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
		/**
		 * 移除当前迭代位置数组元素
		 * 注意:在迭代集合元素时,如果未进行取值操作,调用该方法,会抛throw new IllegalStateException()	
		 * 因为该方法是根据lastRet值判断当前元素位置,lastRet初始值为-1,next()会重新赋值lastRet 
		 */
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
		/**
		 * 函数式接口实现	
		 */
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }
		/**
		 * 集合在迭代期间,不能有增加、删除元素操作,保证迭代数据的准确性
		 */
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
  1. 实现了ListIterator接口的迭代器。该迭代器提供双向迭代功能(正向遍历和反向遍历),支持从数组任一位置开始遍历。新增add方法,使迭代器在迭代过程中可动态新增元素。
private class ListItr extends Itr implements ListIterator<E> {
		/**
		 * 定义迭代器光标初始位置
		 */
        ListItr(int index) {
            super();
            cursor = index;
        }
		/**
		 * 判断当前元素向前回溯,是否有下一个元素	
		 */
        public boolean hasPrevious() {
            return cursor != 0;
        }
		/**
		 * 返回光标索引	
		 */
        public int nextIndex() {
            return cursor;
        }
		/**
		 * 返回当前元素的上一个元素索引值	
		 */
        public int previousIndex() {
            return cursor - 1;
        }
		/**
		 * 取数组当前元素的上一个元素
		 */
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }
		/**
		 * 重新设置当前元素的值
		 */
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
		/**
		  * 在当前元素索引处新增元素,将当前元素及其后继元素依次向后移一位
 		  */
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }
  1. 实现了Spliterator接口的可分割迭代器ArrayListSpliterator,JDK1.8新特性,增加集合并行迭代元素的能力。

上文提及到,在使用迭代器迭代元素时,不允许调用非迭代器的方法进行新增、删除操作。请看Itr和ListItr迭代器的实现,其内部有成员变量expectedModCount=modCount,使用迭代器增、删、改、查集合元素时,会调用checkForComodification方法,该方法通过判断modCount != expectedModCount,若为true,则抛出ConcurrentModificationException,保证了在使用迭代器迭代集合期间内,迭代元素的准确性。
还有一点,我们知道了ArrayList是动态数组的实现,而动态数组可动态改变数组长度。使用add方法新增元素,会进行数组扩容,增加数组长度;使用System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 方法会进行数组复制,但只会改变数组存储的元素,不会改变数组长度。那如何缩短数组长度呢?ArrayList提供了trimToSize()方法,可惜的是,ArrayList内的所有方法都没有调用过该方法(包括remove)。也即是说,只能开发人员自己调用该方法缩短数组长度。

public void trimToSize() {
        modCount++;
        // 只有在数组存储的元素个数小于数组长度时,调用该方法才能生效
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }

ArrayList优缺点

ArrayList就是实现动态数组的集合类。查找、修改可直接通过定位数组索引进行操作,时间复杂度为O(1);增加、删除会复制、扩容数组,实质是调用System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length); 实现,通过阅读相关博客和论坛,知道此方法是通过JVM内存复制实现的,但内存复制也只能一块一块复制。所耗系统资源仍然很多。所以,需要查找、修改多,增加、删除少的集合操作,可选择ArrayList。

Vector

和ArrayList相比,Vector也是实现动态数组的集合类。但它是线程安全的。涉及到调用成员变量的方法,都被Synchronized关键字修饰。

// 获取元素
public synchronized E get(int index);
// 修改元素
public synchronized E set(int index, E element);
// 新增元素
public synchronized boolean add(E e);
// 删除元素
public synchronized boolean removeElement(Object obj);
// 集合转换为数组
public synchronized Object[] toArray();
// 从指定位置开始,获取存储元素对象为o的索引位置
public synchronized int indexOf(Object o, int index);

LinkedList

LinkedList数据结构

LinkedList是一个双向链表,实现了Deque接口,具有双端队列特性。可用作链表、栈、队列。
双端队列:是一种具有队列和栈性质的线性数据结构,查找、增加和删除操作只能在两端进行。
阅读源码,分析LinkedList是如何实现双向链表的。
LinkedList的继承结构:

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

LinkedList继承自AbstractSequentialList。

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

AbstractSequentialList又继承自AbstractList,这代表该类和AbstractList一样,具有“随机访问”数据的能力。但和AbstractList不同的是,AbstractList是根据数组特性实现随机访问,通过确定数组索引值,能够在常数时间内确定访问的元素。而AbstractSequentialList是一种链表结构,实现“随机访问”特性是通过迭代器来实现的,只能通过“顺序访问”迭代数据,间接实现“随机访问”。也即是说,继承该类的集合,是一种链表存储结构,支持元素“随机访问”的能力。
Deque接口
Deque接口,定义了双端队列特性,支持两端元素的插入和删除。

public interface Deque<E> extends Queue<E> {
	/**
	 *
	 */
	// 在双端队列头部插入元素
	void addFirst(E e);
	// 在双端队列尾部插入元素
	void addLast(E e);
	// 删除双端队列的第一个元素
	E removeFirst();
	// 删除双端队列的最后一个元素
	E removeLast();
	// 获取双端队列的第一个元素,但不移除
	E getFirst();
	// 获取双端队列的最后一个元素,但不移除
	E getLast();
	// 获取并删除双端队列的第一个元素
	E pollFirst();
	// 获取并删除双端队列的最后一个元素
	E pollLast();
	// 从这个deque表示的堆栈中弹出第一个元素
	E pop();
	// 推入一个元素到deque表示的堆栈中
	void push(E e);
	// 双向迭代器
	Iterator<E> iterator();
	// 以倒序返回此双端队列中的元素的迭代器
	Iterator<E> descendingIterator();
}

上文提到,LinkedList继承自AbstractSequentialList,这说明LinkedList是链表数据结构,且支持“顺序访问”和“随机访问”。又实现了Deque接口,具有双端队列特性,支持两端元素插入和删除。那么什么样的数据结构,能够同时满足这些特性呢?那就是双向链表。
链表节点:
LinkedList内部定义了Node<E>内部类,该类是双向链表上的一个结点,是LinkedList<E>集合元素的实际存储区,具有前驱结点指针和后继结点指针,以支持双向访问数据的能力。对LinkedList的操作,本质上是对结点指针的操作,后面将会逐步体现这一特点。

private static class Node<E> {
		// LinkedList集合存储的对象的指针。
        E item;
        // 前驱结点指针
        Node<E> next;
        // 后继结点指针
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

链表结构需要有头结点和尾结点,代表链表的起始和结束。还需要有记录结点个数的字段,方便统计并且支持“随机访问”插入结点时,根据该字段判断插入结点位置是否正确。

// 初始值为0,记录Node节点个数
transient int size = 0;
// 头结点
transient Node<E> first;
// 尾节点
transient Node<E> last;

LinkedList是如何实现“随机访问”特性:
node(int index)方法。参数index:代表链表从头结点起到尾结点,第index个结点位置。
该方法实现方式和二分查找有些类似,通过将链表分割成平均的2部分,判断查找元素所属的那部分链表,在该部分链表进行遍历,避免了全局遍历。平均时间复杂度为O(logn)

Node<E> node(int index) {
        // assert isElementIndex(index);
        // 从头结点first → size>>1 遍历
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
		// 从size>>1 → 尾结点 遍历
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

LinkedList有2种创建方式:

  1. 无参构造函数,创建一个空链表
public LinkedList() {
    }
  1. 有参构造函数,参数是一个Collection集合对象,通过将Collection转换为数组,遍历转换的数组,逐个存储在LinkedList中
public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }
public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
public boolean addAll(int index, Collection<? extends E> c) {
		// 检测插入位置是否正确,LinkedList支持在链表任一节点处都可以插入新节点,需满足index >= 0 && index <= size
        checkPositionIndex(index);
		// 将Collection集合转换为数组
        Object[] a = c.toArray();
        // 集合元素c的长度
        int numNew = a.length;
        // 若长度为0,表示c是一个空元素集合,返回false,插入失败
        if (numNew == 0)
            return false;
        // pred:index结点的前驱结点;succ:索引index结点
        Node<E> pred, succ;
        // index == size,选择在链表尾部插入结点,后继结点为空,前驱结点为尾结点
        if (index == size) {
            succ = null;
            pred = last;
        // 在链表头或链表中间处插入结点
        } else {
            succ = node(index);
            pred = succ.prev;
        }
		// 遍历数组,循环插入到链表中
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }
		// 在index处插入结点后,拼接原index结点及其后继结点
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }
/**
 * 检测插入位置是否正确
 */
private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

LinkedList如何实现Deque接口,具有双端队列特性。

/**
 * 获取双端队列第一个结点
 */
public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
/**
 * 获取双端队列最后一个结点
 */
public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
/**
 * 在双端队列头部新增结点
 */
public void addFirst(E e) {
        linkFirst(e);
    }
/**
 * 在双端队列尾部新增结点
 */
public void addLast(E e) {
        linkLast(e);
    }
/**
 * 在链表头部新增结点
 */
private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
/**
 * 在链表尾部新增结点
 */
void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
/**
 * 获取并删除双端队列第一个结点
 */
public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
/**
 * 获取并删除双端队列最后一个结点
 */
public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
/**
 * 删除非空链表头结点并返回
 */
private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }
/**
 * 删除非空链表尾结点并返回
 */
private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }

可以看到,LinkedList实现了Deque接口,可以在链表两端进行查找、增加和删除操作。
但还没有完全实现双端队列,双端队列支持正向遍历和反向遍历。接下来看LinkedList迭代器是如何实现元素的正向遍历和反向遍历的。
双向迭代器——ListItr

private class ListItr implements ListIterator<E> {
		// 光标结点
        private Node<E> lastReturned;
        /**
          * 未调用next()或previours()取值前,表示光标结点;
          * 取值后,如若正向取值,代表光标结点的后继节点;若反向取值,代表光标结点的反向结点
          */
        private Node<E> next;
        // nextIndex,正向遍历:光标结点的后继节点的索引;反向遍历:光标结点的前驱结点的索引
        private int nextIndex;
        // 
        private int expectedModCount = modCount;
		/**
		 * 构造函数。index决定,迭代器从链表的哪个结点开始遍历元素
		 */
        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }
		/**
		 * 正向遍历,链表中是否还有更多的结点
		 */
        public boolean hasNext() {
            return nextIndex < size;
        }
		/**
		 * 返回光标结点,并且前进光标位置
		 */
        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }
		/**
		 * 反向遍历,链表中是否还有更多的结点
		 */
        public boolean hasPrevious() {
            return nextIndex > 0;
        }
		/**
		 * 返回光标结点,并向前移动光标位置。 
		 */
        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }
		// 返回光标结点的索引
        public int nextIndex() {
            return nextIndex;
        }
		/**
		 * 光标结点的前驱结点的索引 
		 */
        public int previousIndex() {
            return nextIndex - 1;
        }
		/**
		 * 从列表中删除由next()或previous()返回的结点
		 * 在未调用next()或previous()前,不能调用该方法
		 */
        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            // 从非空列表中删除节点
            unlink(lastReturned);
            // 未调用next()或previours()取元素
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }
		/**
		 * 修改光标结点
		 */
        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }
		/**
		 * 在当前光标节点处,插入新节点
		 */
        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
            	// 在链表尾部插入节点
                linkLast(e);
            else
            	// 在当前光标节点处,插入前置节点
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }
		/**
		 * 集合在迭代期间,不能使用非迭代器方法增加或删除结点,保证迭代数据的准确性
		 */
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    /**
	 * 在succ结点处,插入前驱结点
	 */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

该迭代器,根据构造函数传入的参数index的值,决定从列表中哪个结点开始遍历,如果index == 0,从头结点开始遍历;index==size,从尾结点开始遍历;0<index<size,从列表中间开始遍历。
hasNext()、next()支持列表正向遍历;hasPrevious()、previous()支持列表反向遍历。
也即是说:LinkedList支持从列表任一节点处开始遍历元素。既可以正向遍历也可以反向遍历。
双端队列也具有栈的特性,只能从一端进栈或出栈。

/**
 1. 入栈
 */
public void push(E e) {
		// 插入头结点
        addFirst(e);
    }
/**
 2. 出栈
 */
public E pop() {
		// 删除头结点
        return removeFirst();
    }

可以看到,LinkedList实现的栈,是从头结点处实现元素的进栈和出栈。
至此,LinkedList已经完全实现了双端队列。其实也完成了双向链表的实现。上文提到过node(int index),支持LinkedList实现“随机访问”特性。而双端队列和双向链表的最大区别就在这里,队列只能从头结点或尾结点取元素,而双向链表支持从任一结点取元素。
LinkedList的优缺点:
优点:
支持多种数据结构:队列、链表、栈。
插入、删除操作可以在常数时间内完成
缺点:
查找元素较慢,最好情况时间复杂度(查询头结点或尾结点)为O(1),平均时间复杂度为O(n/2)。

ArrayList和LinkedList的比较

相同点:

  1. 是一种有序集合。
  2. 都可以存储null元素。
  3. 都可存储重复的元素。

不同点:

  1. 数据结构不同
    ArrayList是一个动态数组。
    LinkedList是一个双向链表。

  2. 集合元素访问方式不同
    ArrayList通过数组下标访问。
    LinkedList通过链表指针访问。

  3. 访问速度不同
    访问一个ArrayList元素,该元素的内存地址 = 数组的基地址 + 元素在数组中的索引 * 每个数组元素占用的内存空间。整个过程需要一次乘法和一次加法,因为这两个运算的执行时间是常数时间,所以可认为访问ArrayList元素操作能在常数时间内完成。时间复杂度为O(1)。

    LinkedList访问是通过遍历元素指针实现的,虽然node(int index)对访问进行了优化,但访问一个元素,平均时间复杂度为O(n/2),最好情况下时间复杂度为O(1)。

  4. 增加、删除元素方式不同
    ArrayList增加、删除元素通过数组的扩容和复制实现,占用系统资源很大。
    LinkedList只需要修改节点的前驱指针和后继指针即可,就是在定位增加或删除结点的位置浪费时间。所以LinkedList的时间复杂度可看作访问一个结点的时间复杂度为O(n/2)。

  5. 适用场景
    ArrayList适用于快速随机访问元素,且元素的增加、删除操作少的情况。
    LinkedList适用于频繁的增加、删除元素,查找、修改元素操作少的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值