关于Deque,之前我的总结是,如果要当作Stack使用,则stick to Stack methods,比如push, pop, peek。如果当作Queue使用,则stick to Queue method,比如add/offer, poll/remove, peek。在实现上,我一般使用的是ArrayDeque, a resizable double-ended array。
今天突然想到一个问题,用Deque实现的Queue或者Stack,在使用enhanced for loop的时候,Java是怎么知道元素弹出的正确顺序呢? 或者如果混用Queue和Stack的方法,peek会弹出什么结果?iterator会给出什么顺序的结果呢?
/** * Pushes an element onto the stack represented by this deque. In other * words, inserts the element at the front of this deque. * * <p>This method is equivalent to {@link #addFirst}. * * @param e the element to push * @throws NullPointerException if the specified element is null */ publicvoidpush(E e) { addFirst(e); }
/** * Inserts the specified element at the front of this deque. * * @param e the element to add * @throws NullPointerException if the specified element is null */ publicvoidaddFirst(E e) { if (e == null) thrownewNullPointerException(); final Object[] es = elements; es[head = dec(head, es.length)] = e; if (head == tail) grow(1); }
/** * Circularly decrements i, mod modulus. * Precondition and postcondition: 0 <= i < modulus. */ staticfinalintdec(int i, int modulus) { if (--i < 0) i = modulus - 1; return i; }
/** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #addLast}. * * @param e the element to add * @return {@code true} (as specified by {@link Collection#add}) * @throws NullPointerException if the specified element is null */ publicbooleanadd(E e) { addLast(e); returntrue; }
/** * Inserts the specified element at the end of this deque. * * <p>This method is equivalent to {@link #add}. * * @param e the element to add * @throws NullPointerException if the specified element is null */ publicvoidaddLast(E e) { if (e == null) thrownewNullPointerException(); final Object[] es = elements; es[tail] = e; if (head == (tail = inc(tail, es.length))) grow(1); }
/** * Circularly increments i, mod modulus. * Precondition and postcondition: 0 <= i < modulus. */ staticfinalintinc(int i, int modulus) { if (++i >= modulus) i = 0; return i; }
peek总是从head pointer取值
1 2 3 4 5 6 7 8 9 10 11 12 13
/** * Retrieves, but does not remove, the head of the queue represented by * this deque, or returns {@code null} if this deque is empty. * * <p>This method is equivalent to {@link #peekFirst}. * * @return the head of the queue represented by this deque, or * {@code null} if this deque is empty */ public E peek() { return peekFirst(); }
iterator总是从head pointer -> tail pointer
1 2 3 4 5 6 7 8 9 10 11 12
/** * Returns an iterator over the elements in this deque. The elements * will be ordered from first (head) to last (tail). This is the same * order that elements would be dequeued (via successive calls to * {@link #remove} or popped (via successive calls to {@link #pop}). * * @return an iterator over the elements in this deque */ public Iterator<E> iterator() { returnnewDeqIterator(); }