Jdk1.8 Collections Framework源码解析(3)-ArrayDeque

表、栈和队列是三种基本的数据结构,前面总结的ArrayList和LinkedList能够做为任意一种数据结构来使用,固然因为实现方式的不一样,操做的效率也会不一样。 这篇要看一下java.util.ArrayDeque。从命名上看,它是一个由数组实现的双端队列。仍是先看一下它实现了哪些接口。java

public class ArrayDeque<E> extends AbstractCollection<E>  
                           implements Deque<E>, Cloneable, Serializable  
{

在看看它的类注释,做者是 大名鼎鼎的 Doug Lea, 大师级的人物,鄙人只能膜拜。上面balbala , biu biu biu ...... 的一大窜,大致是说,java.util.ArrayDeque是Deque接口的动态数组实现,容量会按需扩展,线程不安全。做为栈使用比java.util.Stack快,做为队列使用比java.util.LinkedList快。大多数的操做消耗常数时间。主要特性就是这些。数组

在看源码的时候,仍是老规矩,若是是你来作的话,你会如何来实现呢?首先,按照注释的来,确定是要有个数组来保存数据啦,没啥好说的。既然是双端的队列,必然有一个前,一个后的指针分别指向首尾。既然是一个数组,那么优点就是在查找上,指针移动的速度就会很快,能够快速的查找到元素的位置。总体的想法大概就是这样。 那么接下来,咱们来看看java.util.ArrayDeque的源码吧。具体的源码的实现。安全

/**
     * The array in which the elements of the deque are stored.
     * The capacity of the deque is the length of this array, which is
     * always a power of two. The array is never allowed to become
     * full, except transiently within an addX method where it is
     * resized (see doubleCapacity) immediately upon becoming full,
     * thus avoiding head and tail wrapping around to equal each
     * other.  We also guarantee that all array cells not holding
     * deque elements are always null.
     */
    private transient E[] elements;

    /**
     * The index of the element at the head of the deque (which is the
     * element that would be removed by remove() or pop()); or an
     * arbitrary number equal to tail if the deque is empty.
     */
    private transient int head;

    /**
     * The index at which the next element would be added to the tail
     * of the deque (via addLast(E), add(E), or push(E)).
     */
    private transient int tail;

    /**
     * The minimum capacity that we'll use for a newly created deque.
     * Must be a power of 2.
     */
    private static final int MIN_INITIAL_CAPACITY = 8;

能够看到,基本上是这样。最后一个常量表示初始化的最小容量,注释说明这个值必须是2的幂,这是为何??, 源码注释是这样说的,不知道为啥, 先记住这个问题,继续往下看。数据结构

/**
     * Constructs an empty array deque with an initial capacity
     * sufficient to hold 16 elements.
     */
    public ArrayDeque() {
        elements = (E[]) new Object[16];
    }

    /**
     * Constructs an empty array deque with an initial capacity
     * sufficient to hold the specified number of elements.
     *
     * @param numElements  lower bound on initial capacity of the deque
     */
    public ArrayDeque(int numElements) {
        allocateElements(numElements);
    }

    /**
     * Constructs a deque containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.  (The first element returned by the collection's
     * iterator becomes the first element, or <i>front</i> of the
     * deque.)
     *
     * @param c the collection whose elements are to be placed into the deque
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayDeque(Collection<? extends E> c) {
        allocateElements(c.size());
        addAll(c);
    }

关注一些注释,一共有3个构造方法。无参的构造方法会建立长度为16的内部数组。接受一个集合的构造方法不用多说了,看一下接受“元素数量”的构造方法,里面会调一个分配内部数组空间的方法。app

/**
     * Allocate empty array to hold the given number of elements.
     *
     * @param numElements  the number of elements to hold
     */
    private void allocateElements(int numElements) {
        int initialCapacity = MIN_INITIAL_CAPACITY;
        // Find the best power of two to hold elements.
        // Tests "<=" because arrays aren't kept full.
        if (numElements >= initialCapacity) {
            initialCapacity = numElements;
            initialCapacity |= (initialCapacity >>>  1);
            initialCapacity |= (initialCapacity >>>  2);
            initialCapacity |= (initialCapacity >>>  4);
            initialCapacity |= (initialCapacity >>>  8);
            initialCapacity |= (initialCapacity >>> 16);
            initialCapacity++;

            if (initialCapacity < 0)   // Too many elements, must back off
                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
        }
        elements = (E[]) new Object[initialCapacity];
    }

这个方法是根据给定numElements来进行内部数组空间的分配。这里有一个前提,容量必须是2的幂,尽管如今还不知道为何必须是2的幂,但先往下看。能够看到若是numElements小于最小容量8的话,就会按最小容量来分配数组空间。若是大于等于8,会到一个条件语句中作一些操做,看下这些操做是干吗的。咱们知道若是一个2进制数是2的幂,那么它的特色就是只有一位是1。this

2^0 = 1  
2^1 = 10  
2^n = 10000...(n个0)
2^1 = 1 + 1  
2^3 = 111 + 1  
2^n = 111...(n个1) + 1
相关文章
相关标签/搜索