privatevoidallocateElements(intnumElements){intinitialCapacity=MIN_INITIAL_CAPACITY;//MIN_INITIAL_CAPACITY = 8// 能容纳numElements个元素的最小的2的幂次方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 offinitialCapacity>>>=1;// Good luck allocating 2 ^ 30 elements}elements=(E[])newObject[initialCapacity];}
扩容策略
double扩容
123456789101112131415
privatevoiddoubleCapacity(){asserthead==tail;intp=head;intn=elements.length;// 当前容量大小intr=n-p;// p右侧元素个数intnewCapacity=n<<1;// 新容量大小if(newCapacity<0)thrownewIllegalStateException("Sorry, deque too big");Object[]a=newObject[newCapacity];System.arraycopy(elements,p,a,0,r);// 数据拷贝System.arraycopy(elements,0,a,r,p);elements=(E[])a;head=0;tail=n;}