Java-Collections Framework学习与总结-ArrayDeque

表、栈和队列是三种基本的数据结构,前面总结的ArrayList和LinkedList可以作为任意一种数据结构来使用,当然由于实现方式的不同,操作的效率也会不同。
        这篇要看一下java.util.ArrayDeque。从命名上看,它是一个由数组实现的双端队列。还是先看一下它实现了哪些接口。
Java代码   收藏代码
  1. public class ArrayDeque<E> extends AbstractCollection<E>  
  2.                            implements Deque<E>, Cloneable, Serializable  
  3. {  

        这些接口都总结过了,不说了。不过我猛然发现了
Java代码   收藏代码
  1. @author  Josh Bloch and Doug Lea  

        为什么其他的是这样
Java代码   收藏代码
  1. @author  Josh Bloch  
  2. @author  Neal Gafter  

        这一切的一切究竟是为什么!!我仿佛听到了中国梦之声现场观众呐喊在一起。。。嘎嘎,开个玩笑。看来这个类是大师们的联手之作喽,赶紧鉴赏下:)
        先读了一下类注释,大概是说,java.util.ArrayDeque是Deque接口的动态数组实现,容量会按需扩展,线程不安全。作为栈使用比java.util.Stack快,作为队列使用比java.util.LinkedList快。大多数的操作消耗常数时间。主要特性就是这些。
        在读源码之前,还是先想一下,如果自己实现会怎么做。首先一定是有一个内部数组用来保存数据;既然是队列,那内部应该有2个指针分别指向首尾,对队列两端的操作可以通过首尾指针的移动来快速进行,可以通过首位指针的位置来算出队列的元素个数等等,大概想法是这样,当然一些细节问题还没考虑。有了大体上的思路,来看下java.util.ArrayDeque的源码吧。
Java代码   收藏代码
  1. /** 
  2.  * The array in which the elements of the deque are stored. 
  3.  * The capacity of the deque is the length of this array, which is 
  4.  * always a power of two. The array is never allowed to become 
  5.  * full, except transiently within an addX method where it is 
  6.  * resized (see doubleCapacity) immediately upon becoming full, 
  7.  * thus avoiding head and tail wrapping around to equal each 
  8.  * other.  We also guarantee that all array cells not holding 
  9.  * deque elements are always null. 
  10.  */  
  11. private transient E[] elements;  
  12.   
  13. /** 
  14.  * The index of the element at the head of the deque (which is the 
  15.  * element that would be removed by remove() or pop()); or an 
  16.  * arbitrary number equal to tail if the deque is empty. 
  17.  */  
  18. private transient int head;  
  19.   
  20. /** 
  21.  * The index at which the next element would be added to the tail 
  22.  * of the deque (via addLast(E), add(E), or push(E)). 
  23.  */  
  24. private transient int tail;  
  25.   
  26. /** 
  27.  * The minimum capacity that we'll use for a newly created deque. 
  28.  * Must be a power of 2. 
  29.  */  
  30. private static final int MIN_INITIAL_CAPACITY = 8;  

        可以看到,基本上是这样。最后一个常量表示初始化的最小容量,注释说明这个值必须是2的幂,这是为什么??先记住这个问题,继续往下看。
Java代码   收藏代码
  1. /** 
  2.  * Constructs an empty array deque with an initial capacity 
  3.  * sufficient to hold 16 elements. 
  4.  */  
  5. public ArrayDeque() {  
  6.     elements = (E[]) new Object[16];  
  7. }  
  8.   
  9. /** 
  10.  * Constructs an empty array deque with an initial capacity 
  11.  * sufficient to hold the specified number of elements. 
  12.  * 
  13.  * @param numElements  lower bound on initial capacity of the deque 
  14.  */  
  15. public ArrayDeque(int numElements) {  
  16.     allocateElements(numElements);  
  17. }  
  18.   
  19. /** 
  20.  * Constructs a deque containing the elements of the specified 
  21.  * collection, in the order they are returned by the collection's 
  22.  * iterator.  (The first element returned by the collection's 
  23.  * iterator becomes the first element, or <i>front</i> of the 
  24.  * deque.) 
  25.  * 
  26.  * @param c the collection whose elements are to be placed into the deque 
  27.  * @throws NullPointerException if the specified collection is null 
  28.  */  
  29. public ArrayDeque(Collection<? extends E> c) {  
  30.     allocateElements(c.size());  
  31.     addAll(c);  
  32. }  

        一共有3个构造方法。无参的构造方法会创建长度为16的内部数组。接受一个集合的构造方法不用多说了,看一下接受“元素数量”的构造方法,里面会调一个分配内部数组空间的方法。
Java代码   收藏代码
  1. /** 
  2.  * Allocate empty array to hold the given number of elements. 
  3.  * 
  4.  * @param numElements  the number of elements to hold 
  5.  */  
  6. private void allocateElements(int numElements) {  
  7.     int initialCapacity = MIN_INITIAL_CAPACITY;  
  8.     // Find the best power of two to hold elements.  
  9.     // Tests "<=" because arrays aren't kept full.  
  10.     if (numElements >= initialCapacity) {  
  11.         initialCapacity = numElements;  
  12.         initialCapacity |= (initialCapacity >>>  1);  
  13.         initialCapacity |= (initialCapacity >>>  2);  
  14.         initialCapacity |= (initialCapacity >>>  4);  
  15.         initialCapacity |= (initialCapacity >>>  8);  
  16.         initialCapacity |= (initialCapacity >>> 16);  
  17.         initialCapacity++;  
  18.   
  19.         if (initialCapacity < 0)   // Too many elements, must back off  
  20.             initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements  
  21.     }  
  22.     elements = (E[]) new Object[initialCapacity];  
  23. }  

        这个方法是根据给定numElements来进行内部数组空间的分配。这里有一个前提, 容量必须是2的幂,尽管现在还不知道为什么必须是2的幂,但先往下看。可以看到如果numElements小于最小容量8的话,就会按最小容量来分配数组空间。如果大于等于8,会到一个条件语句中做一些操作,看下这些操作是干嘛的。我们知道如果一个2进制数是2的幂,那么它的特点就是只有一位是1。
Java代码   收藏代码
  1. 2^0 = 1  
  2. 2^1 = 10  
  3. 2^n = 10000...(n个0)  

        观察代码里有个initialCapacity++,我们可以想到如果一个二进制数+1得到的数是2的幂,如果这个数不是0,那么它的所有位一定都是1。
Java代码   收藏代码
  1. 2^1 = 1 + 1  
  2. 2^3 = 111 + 1  
  3. 2^n = 111...(n个1) + 1  

        所以看下前面的操作,numElements和numElements逻辑右移1位后的数进行与操作,然后赋给numElements。如果把numElements用二进制来表示,相当于把numElements中是1的最高位右边的一位变成1;接下来和numElements逻辑右移2位后的数进行与操作,相当于把最初numElements后面的第三位第四位变成1。。。依次类推,最终会将最高位1右边的31位都变成1(如果有这么多位的话)。
Java代码   收藏代码
  1. 10000000000000000000000000000000  
  2. 经过上面操作变成  
  3. 11111111111111111111111111111111  

        总之上面的操作是要得到大于numElements的最小的2的幂。当然要考虑溢出情况,所以当处理后的numElements小于0时(其实只有一种情况就是10000000000000000000000000000000),将numElements逻辑右移1位,变成2的30次方。
        接下来看下操作方法。
Java代码   收藏代码
  1. // The main insertion and extraction methods are addFirst,  
  2. // addLast, pollFirst, pollLast. The other methods are defined in  
  3. // terms of these.  
  4.   
  5. /** 
  6.  * Inserts the specified element at the front of this deque. 
  7.  * 
  8.  * @param e the element to add 
  9.  * @throws NullPointerException if the specified element is null 
  10.  */  
  11. public void addFirst(E e) {  
  12.     if (e == null)  
  13.         throw new NullPointerException();  
  14.     elements[head = (head - 1) & (elements.length - 1)] = e;  
  15.     if (head == tail)  
  16.         doubleCapacity();  
  17. }  

        看一下最上面的注释,看来只要重点瞅瞅addFirst,addLast, pollFirst, pollLast这几个方法就行了。
        先看看addFirst方法,这方法里最怪异就是head = (head - 1) & (elements.length - 1)这句了。仔细分析一下,既然head相当于一个指针,那么不管head向那个方向移动,它总会移动到内部数组的一端,那么下一次移动它应该绕回到另一端,形成一个回环。幸运的是,当插入第一个值的时候,正好是“绕回”的逻辑。因为这时head默认值是0,head-1就是-1,看到-1我们马上回想到一大串1吧(除非你不知道Java是用补码的。。),-1和一个数做“与”操作结果就是那个数喽,所以这里的结果就是elements.length - 1。
        看到这里会发现,head指针是从后往前的。继续,假设elements.length等于8,elements.length - 1就是7,插入第二个元素的时候,head是7了。再算一下刚才那个表达式,(7-1)&7=6,果然是这样,head又从后往前行进一位。考虑一下为什么要这样写,因为head要从后往前移动,所以每次减1。设想一下,如果head大于1,那么head-1%elements.length也能完成上面的工作。再想一下,如果elements.length是2的幂,那么elements.length-1的二进制形式不就是一串0就加上一串1么,head-1再和这个数做&操作不正好就是head-1(当head>1时)。其实当a是2的幂的时候,b%a可以写成b&(a-1),而且&操作要比%操作性能好一点点。况且,这样写也正好能使得当head=0时移动到数组尾部。
        好了,再看看addLast方法。
Java代码   收藏代码
  1. /** 
  2.  * Inserts the specified element at the end of this deque. 
  3.  * 
  4.  * <p>This method is equivalent to {@link #add}. 
  5.  * 
  6.  * @param e the element to add 
  7.  * @throws NullPointerException if the specified element is null 
  8.  */  
  9. public void addLast(E e) {  
  10.     if (e == null)  
  11.         throw new NullPointerException();  
  12.     elements[tail] = e;  
  13.     if ( (tail = (tail + 1) & (elements.length - 1)) == head)  
  14.         doubleCapacity();  
  15. }  

        addLast先赋值,后移动指针。这点和addFirst不一样。具体的移动方式类似。可以想象,head是从后往前移动,tail从前往后移动。当他们相遇的时候,说明内部数组里已经放满了元素。这时候该扩容啦。
Java代码   收藏代码
  1. /** 
  2.  * Double the capacity of this deque.  Call only when full, i.e., 
  3.  * when head and tail have wrapped around to become equal. 
  4.  */  
  5. private void doubleCapacity() {  
  6.     assert head == tail;  
  7.     int p = head;  
  8.     int n = elements.length;  
  9.     int r = n - p; // number of elements to the right of p  
  10.     int newCapacity = n << 1;  
  11.     if (newCapacity < 0)  
  12.         throw new IllegalStateException("Sorry, deque too big");  
  13.     Object[] a = new Object[newCapacity];  
  14.     System.arraycopy(elements, p, a, 0, r);  
  15.     System.arraycopy(elements, 0, a, r, p);  
  16.     elements = (E[])a;  
  17.     head = 0;  
  18.     tail = n;  
  19. }  

        基本上就是内部数组的容量扩充到之前的2倍,还能保证长度是2的幂。然后是数组的拷贝及指针的重定位。
        有了前面addFirst和addLast的分析,pollFirst和pollLast也很容易看懂了,只是逆过程而已。
        ok,代码分析到这里,其他部分也应该很容易看懂。看来程序中如果有用到简单的栈或者队列的地方,可以考虑下这个类喽!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值