Guest User

Untitled

a guest
Jun 26th, 2018
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 54.95 KB | None | 0 0
  1. /*
  2.  * Written by Alexander Foster and released into the public domain
  3.  * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
  4.  * Portions of this class were adapted from ArrayDeque.
  5.  */
  6. package common.collections;
  7.  
  8. import java.io.Serializable;
  9. import java.util.AbstractCollection;
  10. import java.util.Arrays;
  11. import java.util.Collection;
  12. import java.util.Comparator;
  13. import java.util.ConcurrentModificationException;
  14. import java.util.Deque;
  15. import java.util.Iterator;
  16. import java.util.List;
  17. import java.util.ListIterator;
  18. import java.util.NoSuchElementException;
  19. import java.util.Objects;
  20. import java.util.RandomAccess;
  21. import java.util.Spliterator;
  22. import java.util.function.Consumer;
  23. import java.util.function.Predicate;
  24. import java.util.function.UnaryOperator;
  25.  
  26. public class IndexedDeque<E> extends AbstractCollection<E> implements Deque<E>, List<E>, Cloneable,
  27.         RandomAccess, Serializable {
  28.     /**
  29.      * The array in which the elements of the deque are stored.
  30.      * The capacity of the deque is the length of this array, which is
  31.      * always a power of two. The array is never allowed to become
  32.      * full, except transiently within an addX method where it is
  33.      * resized (see doubleCapacity) immediately upon becoming full,
  34.      * thus avoiding head and tail wrapping around to equal each
  35.      * other.  We also guarantee that all array cells not holding
  36.      * deque elements are always null.
  37.      */
  38.     transient E[] elements; // non-private to simplify nested class access
  39.     /**
  40.      * The index of the element at the head of the deque (which is the
  41.      * element that would be removed by remove() or pop()); or an
  42.      * arbitrary number equal to tail if the deque is empty.
  43.      */
  44.     transient int head;
  45.     /**
  46.      * The index at which the next element would be added to the tail
  47.      * of the deque (via addLast(E), or add(E)).
  48.      */
  49.     transient int tail;
  50.     /**
  51.      * The minimum capacity that we'll use for a newly created deque.
  52.      * Must be a power of 2.
  53.      */
  54.     private static final int MIN_INITIAL_CAPACITY = 8;
  55.  
  56.     // ******  Array allocation and resizing utilities ******
  57.  
  58.     /**
  59.      * Allocates empty array to hold the given number of elements.
  60.      *
  61.      * @param numElements  the number of elements to hold
  62.      */
  63.     @SuppressWarnings("unchecked")
  64.     private void allocateElements(int numElements) {
  65.         int initialCapacity = MIN_INITIAL_CAPACITY;
  66.         // Find the best power of two to hold elements.
  67.         // Tests "<=" because arrays aren't kept full.
  68.         if (numElements >= initialCapacity) {
  69.             initialCapacity = Integer.highestOneBit(numElements) << 1;
  70.             if(initialCapacity < 0) throw new IllegalStateException("Sorry, deque too big");
  71.         }
  72.         elements = (E[])new Object[initialCapacity];
  73.     }
  74.     /**
  75.      * Doubles the capacity of this deque.  Call only when full, i.e.,
  76.      * when head and tail have wrapped around to become equal.
  77.      */
  78.     void doubleCapacity() {
  79.         assert head == tail;
  80.         int p = head;
  81.         int n = elements.length;
  82.         int r = n - p;
  83.         int newCapacity = n << 1;
  84.         if (newCapacity < 0) throw new IllegalStateException("Sorry, deque too big");
  85.         @SuppressWarnings("unchecked")
  86.         E[] a = (E[])new Object[newCapacity];
  87.         System.arraycopy(elements, p, a, 0, r);
  88.         System.arraycopy(elements, 0, a, r, p);
  89.         elements = a;
  90.         head = 0;
  91.         tail = n;
  92.     }
  93.     /**
  94.      * Copies the elements from our element array into the specified array,
  95.      * in order (from first to last element in the deque).  It is assumed
  96.      * that the array is large enough to hold all elements in the deque.
  97.      *
  98.      * @return its argument
  99.      */
  100.     <T> T[] copyElements(T[] a, int from, int to) {
  101.         if (from < to) {
  102.             System.arraycopy(elements, from, a, 0, to - from);
  103.         } else if (from > to) {
  104.             int headPortionLen = elements.length - from;
  105.             System.arraycopy(elements, from, a, 0, headPortionLen);
  106.             System.arraycopy(elements, 0, a, headPortionLen, to);
  107.         }
  108.         return a;
  109.     }
  110.     /**
  111.      * Constructs an empty indexed deque.
  112.      */
  113.     @SuppressWarnings("unchecked")
  114.     public IndexedDeque() {
  115.         elements = (E[])new Object[16];
  116.     }
  117.     /**
  118.      * Constructs an empty indexed deque with an initial capacity
  119.      * sufficient to hold the specified number of elements.
  120.      *
  121.      * @param numElements  lower bound on initial capacity of the deque
  122.      */
  123.     public IndexedDeque(int numElements) {
  124.         allocateElements(numElements);
  125.     }
  126.     /**
  127.      * Constructs a deque containing the elements of the specified
  128.      * collection, in the order they are returned by the collection's
  129.      * iterator.  (The first element returned by the collection's
  130.      * iterator becomes the first element, or <i>front</i> of the
  131.      * deque.)
  132.      *
  133.      * @param c the collection whose elements are to be placed into the deque
  134.      * @throws NullPointerException if the specified collection is null
  135.      */
  136.     public IndexedDeque(Collection<? extends E> c) {
  137.         allocateElements(c.size());
  138.         addAll(c);
  139.     }
  140.     /**
  141.      * Inserts the specified element at the front of this deque.
  142.      *
  143.      * @param e the element to add
  144.      */
  145.     @Override
  146.     public void addFirst(E e) {
  147.         elements[head = (head - 1) & (elements.length - 1)] = e;
  148.         if (head == tail) doubleCapacity();
  149.     }
  150.     /**
  151.      * Inserts the specified element at the end of this deque.
  152.      *
  153.      * <p>This method is equivalent to {@link #add}.
  154.      *
  155.      * @param e the element to add
  156.      */
  157.     @Override
  158.     public void addLast(E e) {
  159.         elements[tail] = e;
  160.         if ((tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity();
  161.     }
  162.     /**
  163.      * Inserts the specified element at the front of this deque.
  164.      *
  165.      * @param e the element to add
  166.      * @return {@code true} (as specified by {@link Deque#offerFirst})
  167.      */
  168.     @Override
  169.     public boolean offerFirst(E e){
  170.         addFirst(e);
  171.         return true;
  172.     }
  173.     /**
  174.      * Inserts the specified element at the end of this deque.
  175.      *
  176.      * @param e the element to add
  177.      * @return {@code true} (as specified by {@link Deque#offerLast})
  178.      */
  179.     @Override
  180.     public boolean offerLast(E e) {
  181.         addLast(e);
  182.         return true;
  183.     }
  184.     /**
  185.      * @throws NoSuchElementException {@inheritDoc}
  186.      */
  187.     @Override
  188.     public E removeFirst() {
  189.         if (isEmpty()) throw new NoSuchElementException();
  190.         return pollFirst();
  191.     }
  192.     /**
  193.      * @throws NoSuchElementException {@inheritDoc}
  194.      */
  195.     @Override
  196.     public E removeLast() {
  197.         if (isEmpty()) throw new NoSuchElementException();
  198.         return pollLast();
  199.     }
  200.     @Override
  201.     public E pollFirst() {
  202.         int h = head;
  203.         if(h == tail) return null;
  204.         E result = elements[h];
  205.         elements[h] = null;
  206.         head = (h + 1) & (elements.length - 1);
  207.         return result;
  208.     }
  209.     @Override
  210.     public E pollLast() {
  211.         int t = tail;
  212.         if(t == head) return null;
  213.         t = (t - 1) & (elements.length - 1);
  214.         E result = elements[t];
  215.         elements[t] = null;
  216.         tail = t;
  217.         return result;
  218.     }
  219.     /**
  220.      * @throws NoSuchElementException {@inheritDoc}
  221.      */
  222.     @Override
  223.     public E getFirst() {
  224.         int h = head;
  225.         if(h == tail) throw new NoSuchElementException();
  226.         return elements[h];
  227.     }
  228.     /**
  229.      * @throws NoSuchElementException {@inheritDoc}
  230.      */
  231.     @Override
  232.     public E getLast() {
  233.         int t = tail;
  234.         if(t == head) throw new NoSuchElementException();
  235.         return elements[(t - 1) & (elements.length - 1)];
  236.     }
  237.     @Override
  238.     public E peekFirst() {
  239.         // elements[head] is null if deque empty
  240.         return elements[head];
  241.     }
  242.     @Override
  243.     public E peekLast() {
  244.         return elements[(tail - 1) & (elements.length - 1)];
  245.     }
  246.     /**
  247.      * Removes the first occurrence of the specified element in this
  248.      * deque (when traversing the deque from head to tail).
  249.      * If the deque does not contain the element, it is unchanged.
  250.      * More formally, removes the first element {@code e} such that
  251.      * {@code o == null ? e == null : o.equals(e)} (if such an element exists).
  252.      * Returns {@code true} if this deque contained the specified element
  253.      * (or equivalently, if this deque changed as a result of the call).
  254.      *
  255.      * @param o element to be removed from this deque, if present
  256.      * @return {@code true} if the deque contained the specified element
  257.      */
  258.     @Override
  259.     public boolean removeFirstOccurrence(Object o) {
  260.         int i = index(o, head, tail);
  261.         if(i == -1) return false;
  262.         delete(i);
  263.         return true;
  264.     }
  265.     /**
  266.      * Removes the last occurrence of the specified element in this
  267.      * deque (when traversing the deque from head to tail).
  268.      * If the deque does not contain the element, it is unchanged.
  269.      * More formally, removes the last element {@code e} such that
  270.      * {@code o == null ? e == null : o.equals(e)} (if such an element exists).
  271.      * Returns {@code true} if this deque contained the specified element
  272.      * (or equivalently, if this deque changed as a result of the call).
  273.      *
  274.      * @param o element to be removed from this deque, if present
  275.      * @return {@code true} if the deque contained the specified element
  276.      */
  277.     @Override
  278.     public boolean removeLastOccurrence(Object o) {
  279.         int i = lastIndex(o, head, tail);
  280.         if(i == -1) return false;
  281.         delete(i);
  282.         return true;
  283.     }
  284.  
  285.     // *** Queue methods ***
  286.    
  287.     /**
  288.      * Inserts the specified element at the end of this deque.
  289.      *
  290.      * <p>This method is equivalent to {@link #addLast}.
  291.      *
  292.      * @param e the element to add
  293.      * @return {@code true} (as specified by {@link Collection#add})
  294.      */
  295.     @Override
  296.     public boolean add(E e) {
  297.         addLast(e);
  298.         return true;
  299.     }
  300.     /**
  301.      * Inserts the specified element at the end of this deque.
  302.      *
  303.      * <p>This method is equivalent to {@link #offerLast}.
  304.      *
  305.      * @param e the element to add
  306.      * @return {@code true} (as specified by {@link Queue#offer})
  307.      */
  308.     @Override
  309.     public boolean offer(E e) {
  310.         return offerLast(e);
  311.     }
  312.     /**
  313.      * Retrieves and removes the head of the queue represented by this deque.
  314.      *
  315.      * This method differs from {@link #poll poll} only in that it throws an
  316.      * exception if this deque is empty.
  317.      *
  318.      * <p>This method is equivalent to {@link #removeFirst}.
  319.      *
  320.      * @return the head of the queue represented by this deque
  321.      * @throws NoSuchElementException {@inheritDoc}
  322.      */
  323.     @Override
  324.     public E remove() {
  325.         return removeFirst();
  326.     }
  327.     /**
  328.      * Retrieves and removes the head of the queue represented by this deque
  329.      * (in other words, the first element of this deque), or returns
  330.      * {@code null} if this deque is empty.
  331.      *
  332.      * <p>This method is equivalent to {@link #pollFirst}.
  333.      *
  334.      * @return the head of the queue represented by this deque, or
  335.      *         {@code null} if this deque is empty
  336.      */
  337.     @Override
  338.     public E poll() {
  339.         return pollFirst();
  340.     }
  341.     /**
  342.      * Retrieves, but does not remove, the head of the queue represented by
  343.      * this deque.  This method differs from {@link #peek peek} only in
  344.      * that it throws an exception if this deque is empty.
  345.      *
  346.      * <p>This method is equivalent to {@link #getFirst}.
  347.      *
  348.      * @return the head of the queue represented by this deque
  349.      * @throws NoSuchElementException {@inheritDoc}
  350.      */
  351.     @Override
  352.     public E element() {
  353.         return getFirst();
  354.     }
  355.     /**
  356.      * Retrieves, but does not remove, the head of the queue represented by
  357.      * this deque, or returns {@code null} if this deque is empty.
  358.      *
  359.      * <p>This method is equivalent to {@link #peekFirst}.
  360.      *
  361.      * @return the head of the queue represented by this deque, or
  362.      *         {@code null} if this deque is empty
  363.      */
  364.     @Override
  365.     public E peek() {
  366.         return peekFirst();
  367.     }
  368.  
  369.     // *** Stack methods ***
  370.  
  371.     /**
  372.      * Pushes an element onto the stack represented by this deque.  In other
  373.      * words, inserts the element at the front of this deque.
  374.      *
  375.      * <p>This method is equivalent to {@link #addFirst}.
  376.      *
  377.      * @param e the element to push
  378.      */
  379.     @Override
  380.     public void push(E e) {
  381.         addFirst(e);
  382.     }
  383.     /**
  384.      * Pops an element from the stack represented by this deque.  In other
  385.      * words, removes and returns the first element of this deque.
  386.      *
  387.      * <p>This method is equivalent to {@link #removeFirst()}.
  388.      *
  389.      * @return the element at the front of this deque (which is the top
  390.      *         of the stack represented by this deque)
  391.      * @throws NoSuchElementException {@inheritDoc}
  392.      */
  393.     @Override
  394.     public E pop() {
  395.         return removeFirst();
  396.     }
  397.    
  398.     // *** List Methods ***
  399.  
  400.     /**
  401.      * @throws IndexOutOfBoundsException {@inheritDoc}
  402.      */
  403.     @Override
  404.     public E get(int index){
  405.         if(index < 0 || index >= size()) throw new IndexOutOfBoundsException();
  406.         return elements[(index + head) & (elements.length - 1)];
  407.     }
  408.     /**
  409.      * @throws IndexOutOfBoundsException {@inheritDoc}
  410.      */
  411.     @Override
  412.     public E set(int index, E e){
  413.         if(index < 0 || index >= size()) throw new IndexOutOfBoundsException();
  414.         index = (index + head) & (elements.length - 1);
  415.         E old = elements[index];
  416.         elements[index] = e;
  417.         return old;
  418.     }
  419.     /**
  420.      * @throws IndexOutOfBoundsException {@inheritDoc}
  421.      */
  422.     @Override
  423.     public void add(int index, E e){
  424.         if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
  425.         insert((index + head) & (elements.length - 1), e);
  426.         if(head == tail) doubleCapacity();
  427.     }
  428.     /**
  429.      * @throws IndexOutOfBoundsException {@inheritDoc}
  430.      */
  431.     @Override
  432.     public E remove(int index){
  433.         if(index < 0 || index >= size()) throw new IndexOutOfBoundsException();
  434.         index = (index + head) & (elements.length - 1);
  435.         E old = elements[index];
  436.         delete(index);
  437.         return old;
  438.     }
  439.     /**
  440.      * @throws NullPointerException if the specified collection is null.
  441.      * @throws IndexOutOfBoundsException {@inheritDoc}
  442.      */
  443.     @Override
  444.     public boolean addAll(int index, Collection<? extends E> c) {
  445.         if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
  446.         Object[] a = c.toArray();
  447.         if(a.length == 0) return false;
  448.         insert(index, a, 0, a.length);
  449.         return true;
  450.     }
  451.     public void clear(int from, int to){
  452.         if(from < 0 || to < from || to > size()) throw new IndexOutOfBoundsException();
  453.         if((to -= from) != 0) delete(from, to);
  454.     }
  455.     @Override
  456.     public int indexOf(Object o) {
  457.         int i = index(o, head, tail);
  458.         return i == -1 ? -1 : (i - head) & (elements.length - 1);
  459.     }
  460.     @Override
  461.     public int lastIndexOf(Object o) {
  462.         int i = lastIndex(o, head, tail);
  463.         return i == -1 ? -1 : (i - head) & (elements.length - 1);
  464.     }
  465.     int index(Object o, int from, int to) {
  466.         E[] a = elements;
  467.         int mask = a.length - 1, i = from;
  468.         if (o == null){
  469.             for( ; i != to; i = (i + 1) & mask){
  470.                 if(a[i] == null) return i;
  471.             }
  472.         } else {
  473.             for( ; i != to; i = (i + 1) & mask){
  474.                 if(o.equals(a[i])) return i;
  475.             }
  476.         }
  477.         return -1;
  478.     }
  479.     int lastIndex(Object o, int to, int from) {
  480.         E[] a = elements;
  481.         int mask = a.length - 1, i = from;
  482.         if (o == null){
  483.             for( ; i != to; ){
  484.                 if(a[i = (i - 1) & mask] == null) return i;
  485.             }
  486.         } else {
  487.             for( ; i != to; ){
  488.                 if(o.equals(a[i = (i - 1) & mask])) return i;
  489.             }
  490.         }
  491.         return -1;
  492.     }
  493.     /**
  494.      * @throws NullPointerException if the specified operator is null.
  495.      */
  496.     @Override
  497.     public void replaceAll(UnaryOperator<E> f){
  498.         replaceAll(f, head, tail);
  499.     }
  500.     <T> void replaceAll(UnaryOperator<E> f, int from, int to){
  501.         Objects.requireNonNull(f);
  502.         E[] a = elements;
  503.         for(int i = from, m = a.length - 1; i != to; i = (i + 1) & m){
  504.             a[i] = f.apply(a[i]);
  505.         }
  506.     }
  507.     /**
  508.      * @throws ClassCastException {@inheritDoc}
  509.      * @throws IllegalArgumentException {@inheritDoc}
  510.      */
  511.     @Override
  512.     public void sort(Comparator<? super E> order){
  513.         sort(order, head, tail);
  514.     }
  515.     @SuppressWarnings("unchecked")
  516.     void sort(Comparator<? super E> order, int from, int to){
  517.         E[] a = elements;
  518.         if(from <= to){
  519.             Arrays.sort(a, from, to, order);
  520.             return;
  521.         }
  522.         if(to == 0){
  523.             Arrays.sort(a, from, a.length, order);
  524.             return;
  525.         }
  526.         int end = a.length - from;
  527.         int size = end + to;
  528.         int t = tail;
  529.         if(t + (long)size <= head){
  530.             System.arraycopy(a, from, a, t, end);
  531.             System.arraycopy(a, 0, a, t + end, to);
  532.             try {
  533.                 Arrays.sort(a, t, t + size, order);
  534.             } catch(RuntimeException | Error e){
  535.                 Arrays.fill(a, t, t + size, null);
  536.                 throw e;
  537.             }
  538.             System.arraycopy(a, t, a, from, end);
  539.             System.arraycopy(a, t + end, a, 0, to);
  540.             Arrays.fill(a, t, t + size, null);
  541.             return;
  542.         }
  543.         E[] e = (E[]) new Object[size];
  544.         System.arraycopy(a, from, e, 0, end);
  545.         System.arraycopy(a, 0, e, end, to);
  546.         Arrays.sort(e, 0, size, order);
  547.         System.arraycopy(e, 0, a, from, end);
  548.         System.arraycopy(e, end, a, 0, to);
  549.     }
  550.     /**
  551.      * @throws IndexOutOfBoundsException {@inheritDoc}
  552.      */
  553.     @Override
  554.     public List<E> subList(int from, int to){
  555.         sublistRangeCheck(size(), from, to);
  556.         return new SubList(null, from, to - from);
  557.     }
  558.     static void sublistRangeCheck(int size, int from, int to){
  559.         if(from < 0) throw new IndexOutOfBoundsException(from + " < 0");
  560.         if(to > size) throw new IndexOutOfBoundsException(to + " > " + size);
  561.         if(from > to) throw new IndexOutOfBoundsException(from + " > " + to);
  562.     }
  563.     private class SubList extends AbstractCollection<E> implements List<E>, RandomAccess {
  564.         final SubList parent;
  565.         final int offset;
  566.         int size;
  567.  
  568.         SubList(SubList parent, int offset, int size) {
  569.             this.parent = parent;
  570.             this.size = size;
  571.             this.offset = offset;
  572.         }
  573.         void addToSize(int s){
  574.             size += s;
  575.             for(SubList p = parent; p != null; p = p.parent){
  576.                 p.size += s;
  577.             }
  578.         }
  579.         @Override
  580.         public E get(int index) {
  581.             if(index < 0 || index >= size) throw new IndexOutOfBoundsException();
  582.             return elements[(offset + head + index) & (elements.length - 1)];
  583.         }
  584.         @Override
  585.         public E set(int index, E e) {
  586.             if(index < 0 || index >= size) throw new IndexOutOfBoundsException();
  587.             index = (offset + head + index) & (elements.length - 1);
  588.             E old = elements[index];
  589.             elements[index] = e;
  590.             return old;
  591.         }
  592.         @Override
  593.         public void add(int index, E e) {
  594.             if(index < 0 || index > size) throw new IndexOutOfBoundsException();
  595.             insert((offset + head + index) & (elements.length - 1), e);
  596.             if(head == tail) doubleCapacity();
  597.             addToSize(1);
  598.         }
  599.         @Override
  600.         public E remove(int index) {
  601.             if(index < 0 || index >= size) throw new IndexOutOfBoundsException();
  602.             index = (offset + head + index) & (elements.length - 1);
  603.             E old = elements[index];
  604.             delete(index);
  605.             addToSize(-1);
  606.             return old;
  607.         }
  608.         @Override
  609.         public boolean addAll(int index, Collection<? extends E> c) {
  610.             if(index < 0 || index > size) throw new IndexOutOfBoundsException();
  611.             Object[] a = c.toArray();
  612.             if(a.length == 0) return false;
  613.             insert(index + offset, a, 0, a.length);
  614.             addToSize(a.length);
  615.             return true;
  616.         }
  617.         @Override
  618.         public List<E> subList(int from, int to) {
  619.             sublistRangeCheck(size, from, to);
  620.             return new SubList(this, from + offset, to - from);
  621.         }
  622.         @Override
  623.         public int size() {
  624.             return size;
  625.         }
  626.         @Override
  627.         public boolean isEmpty() {
  628.             return size == 0;
  629.         }
  630.         @Override
  631.         public void clear() {
  632.             if(size == 0) return;
  633.             delete(offset, size);
  634.             addToSize(-size);
  635.         }
  636.         @Override
  637.         public boolean contains(Object o) {
  638.             int m = elements.length - 1, s = (offset + head) & m;
  639.             return index(o, s, (s + size) & m) != -1;
  640.         }
  641.         @Override
  642.         public Object[] toArray() {
  643.             int m = elements.length - 1, s = (offset + head) & m;
  644.             return copyElements(new Object[size], s, (s + size) & m);
  645.         }
  646.         @SuppressWarnings("unchecked")
  647.         @Override
  648.         public <T> T[] toArray(T[] a) {
  649.             if (a.length < size)
  650.                 a = (T[])java.lang.reflect.Array.newInstance(
  651.                         a.getClass().getComponentType(), size);
  652.             int m = elements.length - 1, s = (offset + head) & m;
  653.             copyElements(a, s, (s + size) & m);
  654.             if (a.length > size) a[size] = null;
  655.             return a;
  656.         }
  657.         @Override
  658.         public boolean add(E e) {
  659.             insert((offset + head + size) & (elements.length - 1), e);
  660.             if(head == tail) doubleCapacity();
  661.             addToSize(1);
  662.             return true;
  663.         }
  664.         @Override
  665.         public boolean remove(Object o) {
  666.             int m = elements.length - 1, s = (offset + head) & m;
  667.             int i = index(o, s, (s + size) & m);
  668.             if(i == -1) return false;
  669.             delete(i);
  670.             addToSize(-1);
  671.             return true;
  672.         }
  673.         @Override
  674.         public boolean removeIf(Predicate<? super E> remove){
  675.             int m = elements.length - 1, s = (offset + head) & m;
  676.             int r = IndexedDeque.this.removeIf(remove, s, (s + size) & m);
  677.             if(r == 0) return false;
  678.             addToSize(-r);
  679.             return true;
  680.         }
  681.         @Override
  682.         public boolean addAll(Collection<? extends E> c) {
  683.             return addAll(size, c);
  684.         }
  685.         @Override
  686.         public boolean containsAll(Collection<?> c) {
  687.             for(Object e : c){
  688.                 if(!contains(e)) return false;
  689.             }
  690.             return true;
  691.         }
  692.         @Override
  693.         public boolean removeAll(Collection<?> c) {
  694.             return removeIf(c::contains);
  695.         }
  696.         @Override
  697.         public boolean retainAll(Collection<?> c) {
  698.             Objects.requireNonNull(c);
  699.             return removeIf(e -> !c.contains(e));
  700.         }
  701.         @Override
  702.         public void replaceAll(UnaryOperator<E> f){
  703.             int m = elements.length - 1, s = (offset + head) & m;
  704.             IndexedDeque.this.replaceAll(f, s, (s + size) & m);
  705.         }
  706.         @Override
  707.         public void forEach(Consumer<? super E> f){
  708.             int m = elements.length - 1, s = (offset + head) & m;
  709.             IndexedDeque.this.forEach(f, s, (s + size) & m);
  710.         }
  711.         @Override
  712.         public void sort(Comparator<? super E> order){
  713.             int m = elements.length - 1, s = (offset + head) & m;
  714.             IndexedDeque.this.sort(order, s, (s + size) & m);
  715.         }
  716.         @Override
  717.         public boolean equals(Object o){
  718.             if(o == this) return true;
  719.             int m = elements.length - 1, s = (offset + head) & m;
  720.             return IndexedDeque.this.equals(o, s, (s + size) & m);
  721.         }
  722.         @Override
  723.         public int hashCode(){
  724.             int m = elements.length - 1, s = (offset + head) & m;
  725.             return IndexedDeque.this.hashCode(s, (s + size) & m);
  726.         }
  727.         @Override
  728.         public int indexOf(Object o) {
  729.             int m = elements.length - 1, s = (offset + head) & m;
  730.             int i = index(o, s, (s + size) & m);
  731.             return i == -1 ? -1 : (i - s) & m;
  732.         }
  733.         @Override
  734.         public int lastIndexOf(Object o) {
  735.             int m = elements.length - 1, s = (offset + head) & m;
  736.             int i = lastIndex(o, s, (s + size) & m);
  737.             return i == -1 ? -1 : (i - s) & m;
  738.         }
  739.         @Override
  740.         public Spliterator<E> spliterator() {
  741.             int m = elements.length - 1, s = (offset + head) & m;
  742.             return new DeqSpliterator(s, (s + size) & m);
  743.         }
  744.         @Override
  745.         public Iterator<E> iterator() {
  746.             return new SubListIterator(0);
  747.         }
  748.         @Override
  749.         public ListIterator<E> listIterator() {
  750.             return new SubListIterator(0);
  751.         }
  752.         @Override
  753.         public ListIterator<E> listIterator(final int index) {
  754.             if(index < 0 || index > size) throw new IndexOutOfBoundsException();
  755.             return new SubListIterator(index);
  756.         }
  757.         class SubListIterator implements ListIterator<E> {
  758.             private final IndexedDeque<E> d = IndexedDeque.this;
  759.             private int cursor, lastRet = -1;
  760.            
  761.             SubListIterator(int index){
  762.                 cursor = index;
  763.             }
  764.             @Override
  765.             public boolean hasNext() {
  766.                 return cursor < size;
  767.             }
  768.             @Override
  769.             public E next() {
  770.                 if(cursor == size) throw new NoSuchElementException();
  771.                 return d.elements[lastRet = (offset + d.head + cursor++) & (d.elements.length - 1)];
  772.             }
  773.             @Override
  774.             public boolean hasPrevious() {
  775.                 return cursor > 0;
  776.             }
  777.             @Override
  778.             public E previous() {
  779.                 if(cursor == 0) throw new NoSuchElementException();
  780.                 return d.elements[lastRet = (offset + d.head + --cursor) & (d.elements.length - 1)];
  781.             }
  782.             @Override
  783.             public int nextIndex() {
  784.                 return cursor;
  785.             }
  786.             @Override
  787.             public int previousIndex() {
  788.                 return cursor - 1;
  789.             }
  790.             @Override
  791.             public void remove() {
  792.                 if(lastRet < 0) throw new IllegalStateException();
  793.                 if(lastRet != ((offset + d.head + cursor) & (d.elements.length - 1))){
  794.                     cursor--;
  795.                 }
  796.                 d.delete(lastRet);
  797.                 lastRet = -1;
  798.                 addToSize(-1);
  799.             }
  800.             @Override
  801.             public void set(E e) {
  802.                 if(lastRet < 0) throw new IllegalStateException();
  803.                 d.elements[lastRet] = e;
  804.             }
  805.             @Override
  806.             public void add(E e) {
  807.                 d.insert((offset + d.head + cursor++) & (d.elements.length - 1), e);
  808.                 if(d.head == d.tail) d.doubleCapacity();
  809.                 addToSize(1);
  810.                 lastRet = -1;
  811.             }
  812.             @Override
  813.             public void forEachRemaining(Consumer<? super E> action){
  814.                 Objects.requireNonNull(action);
  815.                 E[] a = d.elements;
  816.                 int s = offset + d.head;
  817.                 int m = a.length - 1, f = (s + cursor) & m, i = (s + size) & m;
  818.                 if(f == i) return;
  819.                 for( ; i != f; i = (i + 1) & m){
  820.                     action.accept(a[i]);
  821.                 }
  822.                 lastRet = (f - 1) & m;
  823.                 cursor = size;
  824.             }
  825.         }
  826.     }
  827.  
  828.     // *** Collection Methods ***
  829.  
  830.     /**
  831.      * Returns the number of elements in this deque.
  832.      *
  833.      * @return the number of elements in this deque
  834.      */
  835.     @Override
  836.     public int size() {
  837.         return (tail - head) & (elements.length - 1);
  838.     }
  839.     /**
  840.      * Returns {@code true} if this deque contains no elements.
  841.      *
  842.      * @return {@code true} if this deque contains no elements
  843.      */
  844.     @Override
  845.     public boolean isEmpty() {
  846.         return head == tail;
  847.     }
  848.     /**
  849.      * Returns an iterator over the elements in this deque.  The elements
  850.      * will be ordered from first (head) to last (tail).  This is the same
  851.      * order that elements would be dequeued (via successive calls to
  852.      * {@link #remove} or popped (via successive calls to {@link #pop}).
  853.      *
  854.      * @return an iterator over the elements in this deque
  855.      */
  856.     @Override
  857.     public Iterator<E> iterator() {
  858.         return new DeqIterator(head);
  859.     }
  860.     @Override
  861.     public ListIterator<E> listIterator() {
  862.         return new DeqIterator(head);
  863.     }
  864.     /**
  865.      * @throws IndexOutOfBoundsException {@inheritDoc}
  866.      */
  867.     @Override
  868.     public ListIterator<E> listIterator(final int index) {
  869.         if(index < 0 || index > size()) throw new IndexOutOfBoundsException();
  870.         return new DeqIterator((index + head) & (elements.length - 1));
  871.     }
  872.     @Override
  873.     public Iterator<E> descendingIterator() {
  874.         return new DeqIterator(tail){
  875.             @Override
  876.             public boolean hasNext() {
  877.                 return hasPrevious();
  878.             }
  879.             @Override
  880.             public E next(){
  881.                 return previous();
  882.             }
  883.             @Override
  884.             public void forEachRemaining(Consumer<? super E> action) {
  885.                 Objects.requireNonNull(action);
  886.                 checkMod();
  887.                 E[] a = elements;
  888.                 int m = a.length - 1, f = start, i = cursor;
  889.                 if(i == f) return;
  890.                 for( ; i != f; ) {
  891.                     action.accept(a[i = (i - 1) & m]);
  892.                 }
  893.                 lastRet = cursor = f;
  894.             }
  895.         };
  896.     }
  897.     private class DeqIterator implements ListIterator<E> {
  898.         /**
  899.          * Index of element to be returned by subsequent call to next.
  900.          */
  901.         int cursor;
  902.         /**
  903.          * Tail and head recorded at construction (also in remove),
  904.          * to stop iterator and also to check for comodification.
  905.          */
  906.         int end = tail, start = head;
  907.         /**
  908.          * Index of element returned by most recent call to next.
  909.          * Reset to -1 if element is deleted by a call to remove.
  910.          */
  911.         int lastRet = -1;
  912.        
  913.         DeqIterator(int index){
  914.             cursor = index;
  915.         }
  916.         @Override
  917.         public boolean hasNext() {
  918.             return cursor != end;
  919.         }
  920.         @Override
  921.         public boolean hasPrevious() {
  922.             return cursor != start;
  923.         }
  924.         @Override
  925.         public int nextIndex() {
  926.             return (cursor - start) & (elements.length - 1);
  927.         }
  928.         @Override
  929.         public int previousIndex() {
  930.             return nextIndex() - 1;
  931.         }
  932.         final void checkMod(){
  933.             if (tail != end || head != start) throw new ConcurrentModificationException();
  934.         }
  935.         @Override
  936.         public E next() {
  937.             int c = cursor;
  938.             if (c == end) throw new NoSuchElementException();
  939.             checkMod();
  940.             E[] a = elements;
  941.             cursor = (c + 1) & (a.length - 1);
  942.             return a[lastRet = c];
  943.         }
  944.         @Override
  945.         public E previous() {
  946.             int c = cursor;
  947.             if (c == start) throw new NoSuchElementException();
  948.             checkMod();
  949.             return elements[lastRet = cursor = (c - 1) & (elements.length - 1)];
  950.         }
  951.         @Override
  952.         public void forEachRemaining(Consumer<? super E> action) {
  953.             Objects.requireNonNull(action);
  954.             checkMod();
  955.             E[] a = elements;
  956.             int m = a.length - 1, i = cursor, f = end;
  957.             if(i == f) return;
  958.             for( ; i != f; i = (i + 1) & m) {
  959.                 action.accept(a[i]);
  960.             }
  961.             lastRet = (f - 1) & m;
  962.             cursor = f;
  963.         }
  964.         @Override
  965.         public void remove() {
  966.             if (lastRet < 0) throw new IllegalStateException();
  967.             checkMod();
  968.             boolean prev = lastRet == cursor;
  969.             if(delete(lastRet)){
  970.                 if(!prev) cursor = (cursor - 1) & (elements.length - 1);
  971.                 end = tail;
  972.             } else {
  973.                 if(prev) cursor = (cursor + 1) & (elements.length - 1);
  974.                 start = head;
  975.             }
  976.             lastRet = -1;
  977.         }
  978.         @Override
  979.         public void set(E e) {
  980.             if (lastRet < 0) throw new IllegalStateException();
  981.             checkMod();
  982.             elements[lastRet] = e;
  983.         }
  984.         @Override
  985.         public void add(E e) {
  986.             checkMod();
  987.             boolean forward = insert(cursor, e);
  988.             if(head == tail){
  989.                 int c = (cursor - start) & (elements.length - 1);
  990.                 doubleCapacity();
  991.                 start = 0;
  992.                 end = tail;
  993.                 cursor = c + 1;
  994.             } else if(forward){
  995.                 cursor = (cursor + 1) & (elements.length - 1);
  996.                 end = tail;
  997.             } else {
  998.                 start = head;
  999.             }
  1000.             lastRet = -1;
  1001.         }
  1002.     }
  1003.     /**
  1004.      * Returns {@code true} if this deque contains the specified element.
  1005.      * More formally, returns {@code true} if and only if this deque contains
  1006.      * at least one element {@code e} such that
  1007.      * {@code o == null ? e == null : o.equals(e)}.
  1008.      *
  1009.      * @param o object to be checked for containment in this deque
  1010.      * @return {@code true} if this deque contains the specified element
  1011.      */
  1012.     @Override
  1013.     public boolean contains(Object o) {
  1014.         return index(o, head, tail) != -1;
  1015.     }
  1016.     /**
  1017.      * Removes a single instance of the specified element from this deque.
  1018.      * If the deque does not contain the element, it is unchanged.
  1019.      * More formally, removes the first element {@code e} such that
  1020.      * {@code o == null ? e == null : o.equals(e)} (if such an element exists).
  1021.      * Returns {@code true} if this deque contained the specified element
  1022.      * (or equivalently, if this deque changed as a result of the call).
  1023.      *
  1024.      * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
  1025.      *
  1026.      * @param o element to be removed from this deque, if present
  1027.      * @return {@code true} if this deque contained the specified element
  1028.      */
  1029.     @Override
  1030.     public boolean remove(Object o) {
  1031.         return removeFirstOccurrence(o);
  1032.     }
  1033.     /**
  1034.      * Removes all of the elements from this deque.
  1035.      * The deque will be empty after this call returns.
  1036.      */
  1037.     @Override
  1038.     public void clear() {
  1039.         int h = head;
  1040.         int t = tail;
  1041.         if(h == t) return;
  1042.         head = tail = 0;
  1043.         if(h < t){
  1044.             Arrays.fill(elements, h, t, null);
  1045.         } else {
  1046.             Arrays.fill(elements, h, elements.length, null);
  1047.             Arrays.fill(elements, 0, t, null);
  1048.         }
  1049.     }
  1050.     /**
  1051.      * @throws NullPointerException if the specified collection is null.
  1052.      */
  1053.     @Override
  1054.     public boolean containsAll(Collection<?> c) {
  1055.         for(Object e : c){
  1056.             if(!contains(e)) return false;
  1057.         }
  1058.         return true;
  1059.     }
  1060.     /**
  1061.      * @throws NullPointerException if the specified collection is null.
  1062.      */
  1063.     @Override
  1064.     public boolean addAll(Collection<? extends E> c) {
  1065.         return addAll(size(), c);
  1066.     }
  1067.     /**
  1068.      * @throws NullPointerException if the specified collection is null.
  1069.      */
  1070.     @Override
  1071.     public boolean removeAll(Collection<?> c) {
  1072.         return removeIf(c::contains);
  1073.     }
  1074.     /**
  1075.      * @throws NullPointerException if the specified collection is null.
  1076.      */
  1077.     @Override
  1078.     public boolean retainAll(Collection<?> c) {
  1079.         Objects.requireNonNull(c);
  1080.         return removeIf(e -> !c.contains(e));
  1081.     }
  1082.     /**
  1083.      * @throws NullPointerException {@inheritDoc}
  1084.      */
  1085.     @Override
  1086.     public void forEach(Consumer<? super E> action){
  1087.         forEach(action, head, tail);
  1088.     }
  1089.     void forEach(Consumer<? super E> action, int from, int to){
  1090.         Objects.requireNonNull(action);
  1091.         E[] a = elements;
  1092.         for(int i = from, m = a.length - 1; i != to; i = (i + 1) & m){
  1093.             action.accept(a[i]);
  1094.         }
  1095.     }
  1096.     /**
  1097.      * @throws NullPointerException {@inheritDoc}
  1098.      */
  1099.     @Override
  1100.     public boolean removeIf(Predicate<? super E> filter){
  1101.         return removeIf(filter, head, tail) != 0;
  1102.     }
  1103.     int removeIf(Predicate<? super E> filter, int from, int to){
  1104.         Objects.requireNonNull(filter);
  1105.         E[] a = elements;
  1106.         int m = a.length - 1, i = from;
  1107.         for( ; ; i = (i + 1) & m){
  1108.             if(i == to) return 0;
  1109.             if(filter.test(a[i])) break;
  1110.         }
  1111.         int r = i;
  1112.         i = (i + 1) & m;
  1113.         for( ; i != to; i = (i + 1) & m){
  1114.             E e = a[i];
  1115.             if(filter.test(e)) continue;
  1116.             a[r] = e;
  1117.             r = (r + 1) & m;
  1118.         }
  1119.         int s = (to - r) & m;
  1120.         delete((r - head) & m, s);
  1121.         return s;
  1122.     }
  1123.     /**
  1124.      * Returns an array containing all of the elements in this deque
  1125.      * in proper sequence (from first to last element).
  1126.      *
  1127.      * <p>The returned array will be "safe" in that no references to it are
  1128.      * maintained by this deque.  (In other words, this method must allocate
  1129.      * a new array).  The caller is thus free to modify the returned array.
  1130.      *
  1131.      * <p>This method acts as bridge between array-based and collection-based
  1132.      * APIs.
  1133.      *
  1134.      * @return an array containing all of the elements in this deque
  1135.      */
  1136.     @Override
  1137.     public Object[] toArray() {
  1138.         return copyElements(new Object[size()], head, tail);
  1139.     }
  1140.     /**
  1141.      * Returns an array containing all of the elements in this deque in
  1142.      * proper sequence (from first to last element); the runtime type of the
  1143.      * returned array is that of the specified array.  If the deque fits in
  1144.      * the specified array, it is returned therein.  Otherwise, a new array
  1145.      * is allocated with the runtime type of the specified array and the
  1146.      * size of this deque.
  1147.      *
  1148.      * <p>If this deque fits in the specified array with room to spare
  1149.      * (i.e., the array has more elements than this deque), the element in
  1150.      * the array immediately following the end of the deque is set to
  1151.      * {@code null}.
  1152.      *
  1153.      * <p>Like the {@link #toArray()} method, this method acts as bridge between
  1154.      * array-based and collection-based APIs.  Further, this method allows
  1155.      * precise control over the runtime type of the output array, and may,
  1156.      * under certain circumstances, be used to save allocation costs.
  1157.      *
  1158.      * <p>Suppose {@code x} is a deque known to contain only strings.
  1159.      * The following code can be used to dump the deque into a newly
  1160.      * allocated array of {@code String}:
  1161.      *
  1162.      *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
  1163.      *
  1164.      * Note that {@code toArray(new Object[0])} is identical in function to
  1165.      * {@code toArray()}.
  1166.      *
  1167.      * @param a the array into which the elements of the deque are to
  1168.      *          be stored, if it is big enough; otherwise, a new array of the
  1169.      *          same runtime type is allocated for this purpose
  1170.      * @return an array containing all of the elements in this deque
  1171.      * @throws ArrayStoreException if the runtime type of the specified array
  1172.      *         is not a supertype of the runtime type of every element in
  1173.      *         this deque
  1174.      * @throws NullPointerException if the specified array is null
  1175.      */
  1176.     @SuppressWarnings("unchecked")
  1177.     @Override
  1178.     public <T> T[] toArray(T[] a) {
  1179.         int size = size();
  1180.         if (a.length < size)
  1181.             a = (T[])java.lang.reflect.Array.newInstance(
  1182.                     a.getClass().getComponentType(), size);
  1183.         copyElements(a, head, tail);
  1184.         if (a.length > size) a[size] = null;
  1185.         return a;
  1186.     }
  1187.     /**
  1188.      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
  1189.      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
  1190.      * deque.
  1191.      *
  1192.      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
  1193.      * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
  1194.      * Overriding implementations should document
  1195.      * the reporting of additional characteristic values.
  1196.      *
  1197.      * @return a {@code Spliterator} over the elements in this deque
  1198.      * @since 1.8
  1199.      */
  1200.     @Override
  1201.     public Spliterator<E> spliterator() {
  1202.         return new DeqSpliterator(-1, -1);
  1203.     }
  1204.     final class DeqSpliterator implements Spliterator<E> {
  1205.         private int fence;  // -1 until first use
  1206.         private int index;  // current index, modified on traverse/split
  1207.  
  1208.         /** Creates new spliterator covering the given array and range. */
  1209.         DeqSpliterator(int origin, int fence) {
  1210.             this.index = origin;
  1211.             this.fence = fence;
  1212.         }
  1213.         private int getFence() { // force initialization
  1214.             int t;
  1215.             if ((t = fence) < 0) {
  1216.                 t = fence = tail;
  1217.                 index = head;
  1218.             }
  1219.             return t;
  1220.         }
  1221.         @Override
  1222.         public DeqSpliterator trySplit() {
  1223.             int t = getFence(), h = index, n = elements.length;
  1224.             if (h != t && ((h + 1) & (n - 1)) != t) {
  1225.                 if (h > t) t += n;
  1226.                 int m = ((h + t) >>> 1) & (n - 1);
  1227.                 return new DeqSpliterator(h, index = m);
  1228.             }
  1229.             return null;
  1230.         }
  1231.         @Override
  1232.         public void forEachRemaining(Consumer<? super E> consumer) {
  1233.             if (consumer == null) throw new NullPointerException();
  1234.             E[] a = elements;
  1235.             int m = a.length - 1, f = getFence(), i = index;
  1236.             index = f;
  1237.             for( ; i != f; i = (i + 1) & m) {
  1238.                 consumer.accept(a[i]);
  1239.             }
  1240.         }
  1241.         @Override
  1242.         public boolean tryAdvance(Consumer<? super E> consumer) {
  1243.             if (consumer == null) throw new NullPointerException();
  1244.             E[] a = elements;
  1245.             int m = a.length - 1, f = getFence(), i = index;
  1246.             if(i == f) return false;
  1247.             index = (i + 1) & m;
  1248.             consumer.accept(a[i]);
  1249.             return true;
  1250.         }
  1251.         @Override
  1252.         public long estimateSize() {
  1253.             int n = getFence() - index;
  1254.             if (n < 0) n += elements.length;
  1255.             return (long) n;
  1256.         }
  1257.         @Override
  1258.         public int characteristics() {
  1259.             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
  1260.         }
  1261.     }
  1262.    
  1263.     // *** Object methods ***
  1264.  
  1265.     @Override
  1266.     public boolean equals(Object o) {
  1267.         return o == this || equals(o, head, tail);
  1268.     }
  1269.     boolean equals(Object o, int from, int to) {
  1270.         if (!(o instanceof List)) return false;
  1271.         List<?> l = (List<?>)o;
  1272.         E[] a = elements;
  1273.         int i = from, m = a.length - 1, s = l.size();
  1274.         if(s != ((to - from) & m)) return false;
  1275.         if(s == 0) return true;
  1276.         if(o instanceof RandomAccess){
  1277.             for(int j = 0; i != to; i = (i + 1) & m){
  1278.                 E e = a[i];
  1279.                 Object c = l.get(j++);
  1280.                 if(!(e == null ? c == null : e.equals(c))) return false;
  1281.             }
  1282.             return true;
  1283.         }
  1284.         ListIterator<?> it = l.listIterator();
  1285.         for( ; ; i = (i + 1) & m){
  1286.             boolean n = it.hasNext();
  1287.             if(i != to != n) return false;
  1288.             if(!n) return true;
  1289.             E e = a[i];
  1290.             Object c = it.next();
  1291.             if(!(e == null ? c == null : e.equals(c))) return false;
  1292.         }
  1293.     }
  1294.     @Override
  1295.     public int hashCode() {
  1296.         return hashCode(head, tail);
  1297.     }
  1298.     int hashCode(int from, int to) {
  1299.         int hashCode = 1;
  1300.         E[] a = elements;
  1301.         int i = from, m = a.length - 1;
  1302.         for( ; i != to; i = (i + 1) & m){
  1303.             E e = a[i];
  1304.             hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
  1305.         }
  1306.         return hashCode;
  1307.     }
  1308.     /**
  1309.      * Returns a copy of this deque.
  1310.      *
  1311.      * @return a copy of this deque
  1312.      */
  1313.     @Override
  1314.     public IndexedDeque<E> clone() {
  1315.         try {
  1316.             @SuppressWarnings("unchecked")
  1317.             IndexedDeque<E> result = (IndexedDeque<E>) super.clone();
  1318.             result.elements = Arrays.copyOf(elements, elements.length);
  1319.             return result;
  1320.         } catch (CloneNotSupportedException e) {
  1321.             throw new AssertionError();
  1322.         }
  1323.     }
  1324.     private static final long serialVersionUID = -8192327985554913705L;
  1325.     /**
  1326.      * Saves this deque to a stream (that is, serializes it).
  1327.      *
  1328.      * @param s the stream
  1329.      * @throws java.io.IOException if an I/O error occurs
  1330.      * @serialData The current size ({@code int}) of the deque,
  1331.      * followed by all of its elements (each an object reference) in
  1332.      * first-to-last order.
  1333.      */
  1334.     private void writeObject(java.io.ObjectOutputStream s)
  1335.             throws java.io.IOException {
  1336.         s.defaultWriteObject();
  1337.  
  1338.         // Write out size
  1339.         s.writeInt(size());
  1340.  
  1341.         // Write out elements in order.
  1342.         int mask = elements.length - 1;
  1343.         for (int i = head; i != tail; i = (i + 1) & mask)
  1344.             s.writeObject(elements[i]);
  1345.     }
  1346.     /**
  1347.      * Reconstitutes this deque from a stream (that is, deserializes it).
  1348.      * @param s the stream
  1349.      * @throws ClassNotFoundException if the class of a serialized object
  1350.      *         could not be found
  1351.      * @throws java.io.IOException if an I/O error occurs
  1352.      */
  1353.     @SuppressWarnings("unchecked")
  1354.     private void readObject(java.io.ObjectInputStream s)
  1355.             throws java.io.IOException, ClassNotFoundException {
  1356.         s.defaultReadObject();
  1357.  
  1358.         // Read in size and allocate array
  1359.         int size = s.readInt();
  1360.         allocateElements(size);
  1361.         head = 0;
  1362.         tail = size;
  1363.  
  1364.         // Read in all elements in the proper order.
  1365.         for (int i = 0; i < size; i++)
  1366.             elements[i] = (E) s.readObject();
  1367.     }
  1368.    
  1369.     // *** Element insertion and deletion  ***
  1370.    
  1371.     /**
  1372.      * Removes the element at the specified position in the elements array,
  1373.      * adjusting head and tail as necessary.  This can result in motion of
  1374.      * elements backwards or forwards in the array.
  1375.      *
  1376.      * <p>This method is called delete rather than remove to emphasize
  1377.      * that its semantics differ from those of {@link List#remove(int)}.
  1378.      *
  1379.      * @return true if elements moved backwards
  1380.      */
  1381.     boolean delete(int i) {
  1382.         final E[] elements = this.elements;
  1383.         final int mask = elements.length - 1;
  1384.         final int h = head;
  1385.         final int t = tail;
  1386.         final int front = (i - h) & mask;
  1387.         final int back  = (t - i) & mask;
  1388.  
  1389.         // Invariant: head <= i < tail mod circularity
  1390.         if (front >= ((t - h) & mask)) throw new ConcurrentModificationException();
  1391.  
  1392.         // Optimize for least element motion
  1393.         if (front < back) {
  1394.             if (h <= i) {
  1395.                 System.arraycopy(elements, h, elements, h + 1, front);
  1396.             } else { // Wrap around
  1397.                 System.arraycopy(elements, 0, elements, 1, i);
  1398.                 elements[0] = elements[mask];
  1399.                 System.arraycopy(elements, h, elements, h + 1, mask - h);
  1400.             }
  1401.             elements[h] = null;
  1402.             head = (h + 1) & mask;
  1403.             return false;
  1404.         } else {
  1405.             if (i < t) { // Copy the null tail as well
  1406.                 System.arraycopy(elements, i + 1, elements, i, back);
  1407.                 tail = t - 1;
  1408.             } else { // Wrap around
  1409.                 System.arraycopy(elements, i + 1, elements, i, mask - i);
  1410.                 elements[mask] = elements[0];
  1411.                 System.arraycopy(elements, 1, elements, 0, t);
  1412.                 tail = (t - 1) & mask;
  1413.             }
  1414.             return true;
  1415.         }
  1416.     }
  1417.     /**
  1418.      * Inserts the element at the specified position in the elements array.
  1419.      * May either shift the element at the specified index and all after forward,
  1420.      * of shift all elements before the index backwards and insert the element
  1421.      * before the index. Caller is responsible for checking if capacity must be doubled.
  1422.      *
  1423.      * @return true if elements moved forward (and tail was incremented)
  1424.      */
  1425.     boolean insert(int i, E e){
  1426.         final E[] elements = this.elements;
  1427.         final int mask = elements.length - 1;
  1428.         int h = head;
  1429.         final int t = tail;
  1430.         final int front = (i - h) & mask;
  1431.         final int back  = (t - i) & mask;
  1432.  
  1433.         // Invariant: head <= i <= tail mod circularity
  1434.         if (front > ((t - h) & mask)) throw new ConcurrentModificationException();
  1435.  
  1436.         // Optimize for least element motion
  1437.         if (front < back) {
  1438.             i = (i - 1) & mask;
  1439.             h = (h - 1) & mask;
  1440.             if (h <= i) {
  1441.                 System.arraycopy(elements, h + 1, elements, h, front);
  1442.             } else { // Wrap around
  1443.                 System.arraycopy(elements, h + 1, elements, h, mask - h);
  1444.                 elements[mask] = elements[0];
  1445.                 System.arraycopy(elements, 1, elements, 0, i);
  1446.             }
  1447.             elements[i] = e;
  1448.             head = h;
  1449.             return false;
  1450.         } else {
  1451.             if (i <= t) {
  1452.                 System.arraycopy(elements, i, elements, i + 1, back);
  1453.             } else { // Wrap around
  1454.                 System.arraycopy(elements, 0, elements, 1, t);
  1455.                 elements[0] = elements[mask];
  1456.                 System.arraycopy(elements, i, elements, i + 1, mask - i);
  1457.             }
  1458.             elements[i] = e;
  1459.             tail = (t + 1) & mask;
  1460.             return true;
  1461.         }
  1462.     }
  1463.     /**
  1464.      * Removes length elements from the elements array starting at index + head (inclusive).
  1465.      *
  1466.      * @return true if elements moved backward (and tail was decreased)
  1467.      */
  1468.     boolean delete(int index, int length){
  1469.         int size = size();
  1470.         int ahead = size - index - length;
  1471.         E[] a = elements;
  1472.         int mask = a.length - 1;
  1473.         int i = (head + index) & mask;
  1474.         int e = (i + length) & mask;
  1475.         if(index <= ahead){
  1476.             if(head <= i){
  1477.                 if(i <= e){
  1478.                     System.arraycopy(a, head, a, e - index, index);
  1479.                     Arrays.fill(a, head, head += length, null);
  1480.                 } else {
  1481.                     if(e >= index){
  1482.                         System.arraycopy(a, head, a, e - index, index);
  1483.                         Arrays.fill(a, head, a.length, null);
  1484.                         Arrays.fill(a, 0, head = e - index, null);
  1485.                     } else {
  1486.                         System.arraycopy(a, i - e, a, 0, e);
  1487.                         System.arraycopy(a, head, a, head + length, index - e);
  1488.                         Arrays.fill(a, head, head += length, null);
  1489.                     }
  1490.                 }
  1491.             } else {
  1492.                 System.arraycopy(a, 0, a, length, i);
  1493.                 int r = a.length - head;
  1494.                 if(length >= r){
  1495.                     System.arraycopy(a, head, a, length - r, r);
  1496.                     Arrays.fill(a, 0, length - r, null);
  1497.                     Arrays.fill(a, head, a.length, null);
  1498.                     head = (head + length) & mask;
  1499.                 } else {
  1500.                     System.arraycopy(a, a.length - length, a, 0, length);
  1501.                     System.arraycopy(a, head, a, head + length, r - length);
  1502.                     Arrays.fill(a, head, head += length, null);
  1503.                 }
  1504.             }
  1505.             return false;
  1506.         } else {
  1507.             if(tail >= e){
  1508.                 if(i <= e){
  1509.                     System.arraycopy(a, e, a, i, ahead);
  1510.                     Arrays.fill(a, tail - length, tail, null);
  1511.                     tail -= length;
  1512.                 } else {
  1513.                     if(a.length >= i + ahead){
  1514.                         System.arraycopy(a, e, a, i, ahead);
  1515.                         Arrays.fill(a, i + ahead, a.length, null);
  1516.                         Arrays.fill(a, 0, tail, null);
  1517.                         tail = (i + ahead) & mask;
  1518.                     } else {
  1519.                         int r = a.length - i;
  1520.                         System.arraycopy(a, e, a, i, r);
  1521.                         System.arraycopy(a, e + r, a, 0, ahead - r);
  1522.                         Arrays.fill(a, ahead - r, tail, null);
  1523.                         tail = ahead - r;
  1524.                     }
  1525.                 }
  1526.             } else {
  1527.                 int f = a.length - e;
  1528.                 System.arraycopy(a, e, a, i, f);
  1529.                 if(length >= tail){
  1530.                     System.arraycopy(a, 0, a, i + f, tail);
  1531.                     Arrays.fill(a, 0, tail, null);
  1532.                     Arrays.fill(a, i + f + tail, a.length, null);
  1533.                     tail = (i + f + tail) & mask;
  1534.                 } else {
  1535.                     System.arraycopy(a, 0, a, i + f, length);
  1536.                     System.arraycopy(a, length, a, 0, tail - length);
  1537.                     Arrays.fill(a, tail - length, tail, null);
  1538.                     tail -= length;
  1539.                 }
  1540.             }
  1541.             return true;
  1542.         }
  1543.     }
  1544.     /**
  1545.      * Inserts length elements from a starting at offset (inclusive) into the
  1546.      * elements array at index + head. May shift elements forwards or backwards
  1547.      * or resize the elements array.
  1548.      */
  1549.     void insert(int index, Object[] a, int offset, int length) {
  1550.         int size = size();
  1551.         int newSize = size + length;
  1552.         if(newSize < 0 || newSize >= 1 << 30){
  1553.             throw new IllegalStateException("Sorry, deque too big");
  1554.         }
  1555.         E[] es = elements;
  1556.         if(newSize >= es.length){
  1557.             allocateElements(newSize);
  1558.             E[] n = elements;
  1559.             if(tail >= head){
  1560.                 System.arraycopy(es, head, n, 0, index);
  1561.                 System.arraycopy(a, offset, n, index, length);
  1562.                 System.arraycopy(es, head + index, n, index + length, size - index);
  1563.             } else {
  1564.                 int r = es.length - head;
  1565.                 if(r < index){
  1566.                     System.arraycopy(es, head, n, 0, r);
  1567.                     System.arraycopy(es, 0, n, r, index - r);
  1568.                     System.arraycopy(a, offset, n, index, length);
  1569.                     System.arraycopy(es, index - r, n, index + length, size - index);
  1570.                 } else {
  1571.                     System.arraycopy(es, head, n, 0, index);
  1572.                     System.arraycopy(a, offset, n, index, length);
  1573.                     System.arraycopy(es, head + index, n, index + length, r - index);
  1574.                     System.arraycopy(es, 0, n, r + length, tail);
  1575.                 }
  1576.             }
  1577.             head = 0;
  1578.             tail = newSize;
  1579.             return;
  1580.         }
  1581.         int back = size - index;
  1582.         int mask = es.length - 1;
  1583.         if(index <= back){
  1584.             int h = head - length;
  1585.             if(h < 0){
  1586.                 int nh = h & mask;
  1587.                 if(index >= -h){
  1588.                     System.arraycopy(es, head, es, nh, -h);
  1589.                     System.arraycopy(es, head - h, es, 0, index + h);
  1590.                     System.arraycopy(a, offset, es, h + index, length);
  1591.                 } else {
  1592.                     System.arraycopy(es, head, es, nh, index);
  1593.                     int f = -h - index;
  1594.                     System.arraycopy(a, offset, es, nh + index, f);
  1595.                     System.arraycopy(a, offset + f, es, 0, length - f);
  1596.                 }
  1597.                 h = nh;
  1598.             } else {
  1599.                 int i = head + index - es.length;
  1600.                 if(i <= 0){
  1601.                     System.arraycopy(es, head, es, h, index);
  1602.                     System.arraycopy(a, offset, es, h + index, length);
  1603.                 } else {
  1604.                     int r = index - i;
  1605.                     System.arraycopy(es, head, es, h, r);
  1606.                     int ni = i - length;
  1607.                     if(ni >= 0){
  1608.                         System.arraycopy(es, 0, es, h + r, length);
  1609.                         System.arraycopy(es, length, es, 0, ni);
  1610.                         System.arraycopy(a, offset, es, ni, length);
  1611.                     } else {
  1612.                         System.arraycopy(es, 0, es, h + r, i);
  1613.                         System.arraycopy(a, offset, es, h + index, -ni);
  1614.                         System.arraycopy(a, offset - ni, es, 0, length + ni);
  1615.                     }
  1616.                 }
  1617.             }
  1618.             head = h;
  1619.         } else {
  1620.             int t = tail + length;
  1621.             if(t > mask){
  1622.                 t &= mask;
  1623.                 if(t >= back){
  1624.                     int f = t - back;
  1625.                     System.arraycopy(es, tail - back, es, f, back);
  1626.                     System.arraycopy(a, offset, es, tail - back, length - f);
  1627.                     System.arraycopy(a, offset + length - f, es, 0, f);
  1628.                 } else {
  1629.                     System.arraycopy(es, tail - t, es, 0, t);
  1630.                     System.arraycopy(es, tail - back, es, es.length - back + t, back - t);
  1631.                     System.arraycopy(a, offset, es, tail - back, length);
  1632.                 }
  1633.             } else {
  1634.                 int i = tail - back;
  1635.                 if(i >= 0){
  1636.                     System.arraycopy(es, i, es, i + length, back);
  1637.                     System.arraycopy(a, offset, es, i, length);
  1638.                 } else {
  1639.                     System.arraycopy(es, 0, es, t - tail, tail);
  1640.                     int ni = i + length;
  1641.                     if(ni >= 0){
  1642.                         System.arraycopy(es, i & mask, es, ni, -i);
  1643.                         System.arraycopy(a, offset, es, i & mask, -i);
  1644.                         System.arraycopy(a, offset - i, es, 0, ni);
  1645.                     } else {
  1646.                         System.arraycopy(es, (i & mask) - ni, es, 0, -i + ni);
  1647.                         System.arraycopy(es, i & mask, es, ni & mask, -ni);
  1648.                         System.arraycopy(a, offset, es, i & mask, length);
  1649.                     }
  1650.                 }
  1651.             }
  1652.             tail = t;
  1653.         }
  1654.     }
  1655. }
Add Comment
Please, Sign In to add comment