JDK source - deque ArrayDeque

0. Introduction

  • Is a boring Monday night, nothing else, I started looking through the code to play, to see the look JDK source code, Hey, shines, this seems to have been ignored before his thing
  • Look at the title also know that I looked at the source code ArrayDeque
  • Well, in order to prevent there do not know (please ignore Gangster), let us first look at the preliminary knowledge (wonderful ah)

0.1 queue

  • First of all we need to know what is the queue (Queue)?

A queue is a special linear form, is special in that it only allows deletion at the front end of the table (Front), while the rear end of insertion, the table (tail), and stack as a queue by the operating linear restriction table. Referred to as the tail end of the end, delete operation will be referred to as head-of-insertion operation.

0.2 Stack

  • Then we need to know what is the stack (Stack)?

Stack (Stack), also known as the stack, which is a linear form of operation is limited. Defining a linear table insertion and deletion operations only in the trailer. This input is called the stack, relatively, and the other end is called the bottom of the stack. To insert a new element, also known as the stack into the stack, push or push, it is a new element into the top element of the above, making the new top of the stack; remove elements from one stack to stack or also known as unstack, it is the top element removed, so that the adjacent element becomes the new top of the stack.

1. Source Structure

  • Since it is about Java source code, then it is surely not a lack of inheritance implementation structure diagram

ArrayDeque

1.1 Queue

  • Queue Interface Generally speaking is to expand the Collection interface, adds the statement queue associated method of operating characteristics

  • boolean add (E e); specified without violating capacity restrictions in the element into this queue, returns true if successful, if no space is available, it is thrown IllegalStateException.

  • boolean offer (E e); in the case without violating the capacity constraints specified element into this queue. Queue capacity is limited when using this method is generally preferable to add, the latter can only be inserted through the elements to raise an exception.

  • E remove();

  • E poll (); Oh poll also remove and add the same offer as remove the queue is empty or if an exception is thrown, the poll returns null

  • E element();

  • E peek (); element and also with add peek and offer the same, if the queue is empty, an exception is thrown, and peek is not thrown directly back null.

1.2 Dectue

  • Deque is supported at both ends of the collection insert and delete elements linear. Literal translation is "double-ended queue" He is an acronym for "double ended queue", and usually pronounced "deck". Most realize there is no fixed limit to the number of elements they may contain, but this interface supports capacity-constrained container and container size limit is not fixed.

  • void addFirst (E e); insertion head of the queue, will be given capacity is insufficient

  • void addLast (E e); insertion end of the queue, will be given capacity is not enough

  • boolean offerFirst (E e); insertion head of the queue, returns true capacity is not enough successful, false

  • boolean offerLast (E e); insertion end of the queue, returns true capacity is not enough successful, false

  • E removeFirst/Last (E e)

  • E pollFirst / Last (E e) from the head and tail elements were removed and returned, is a supra Yuan Shu not being given a return null

  • E getFirst / Last (E e);

  • E peekFirst / Last (E e)

  • In addition to the above conventional method and the like but also have peek push pop,

1.3 ArrayDeque

  • Method schematic class

  • Not difficult to see, mainly operating on the queue and stack. Here I will talk about this in detail to talk about the realization of the class

2. ArrayDeque data structure

Fields

  • ArrayDeque essence, is an expansion of an array of designs, which contains the head and tail (I used to call the head and tail pointer) he can be used to make double-ended queue can also be used to make the stack, and his realization which made twice the expansion mechanism (with a shift operator to do with HashMap) to ensure its scalability.
  • Also note that it is not thread-safe, it does not do any source synchronous operation.
  • Deque array mainly as a carrier, after the increase with the variation element is deleted by moving the recording head and tail pointers to FIG.

2.1 Constructor

    public ArrayDeque() {
        elements = new Object[16];
    }
    public ArrayDeque(int numElements) {
        allocateElements(numElements);
    }
    public ArrayDeque(Collection<? extends E> c) {
        allocateElements(c.size());
        addAll(c);
    }
    private void allocateElements(int numElements) {
        elements = new Object[calculateSize(numElements)];
    }
    private static int calculateSize(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
        }
        return initialCapacity;
    }
复制代码
  • As can be seen, no default configuration parameter assigns a default capacity size is 16

  • If it developed to calculate how many elements will be greater than the value of the most recent index 2 times

  • Pass pass directly set size also calculation capacity

  • After creating an object corresponding to a default value of int is 0, the head and tail and front correction tail (rear) shown in FIG.

  • In the double-ended queue, front and always points to the location of the current team first element
  • The next position tail (rear) always points to the team last element is the team's position

2.2 additional element method

  • Since the deque queue may be used as it is also used as a method of adding a stack of several elements, which are essentially similar but

  • addFirst team head element increases

    public void addFirst(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[head = (head - 1) & (elements.length - 1)] = e;
        if (head == tail)
            doubleCapacity();
    }
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }
复制代码

  • As can be seen from this deque is no way to put a null value. And offerFirst is a method and addFirst

  • Because this method is to increase the element (head - 1) from the team head & (elements.length - 1) to explain here, this place is the length of how much power is 2, and if the time minus 1 binary representation for the whole 1 equivalent to a head after 1 minus negative he will automatically place the array length-1 even if the appearance. This place will achieve a circular queue

  • addLast increase the tail element

    public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[tail] = e;
        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
            doubleCapacity();
    }
复制代码
  • With addFirst addLast method is similar to the corresponding offerFirst call

  • Here to talk about this expansion doubleCapacity starting with the proviso that when the queue adds an element, tail has a value equal to the front of the lack of space starting expansion, expansion of the following methods

    private void doubleCapacity() {
        assert head == tail;
        int p = head;
        int n = elements.length;
        int r = n - p; // number of elements to the right of p
        int newCapacity = n << 1;
        if (newCapacity < 0)
            throw new IllegalStateException("Sorry, deque too big");
        Object[] a = new Object[newCapacity];
        System.arraycopy(elements, p, a, 0, r);
        System.arraycopy(elements, 0, a, r, p);
        elements = a;
        head = 0;
        tail = n;
    }
复制代码
  • It is to use the System.arraycopy head to length-1 replication in front of the new array, 0 to copy immediately behind the tail.

The method of removal elements 2.3

  • pollFisrt pollLast and removal operations on an array element is also substantially similar
    public E pollFirst() {
        int h = head;
        @SuppressWarnings("unchecked")
        E result = (E) elements[h];
        // Element is null if deque empty
        if (result == null)
            return null;
        elements[h] = null;     // Must null out slot
        head = (h + 1) & (elements.length - 1);
        return result;
    }

    public E pollLast() {
        int t = (tail - 1) & (elements.length - 1);
        @SuppressWarnings("unchecked")
        E result = (E) elements[t];
        if (result == null)
            return null;
        elements[t] = null;
        tail = t;
        return result;
    }
复制代码
  • The removeLast removeFirst offerLast offerFirst are respectively corresponding method called poll

The method of obtaining the element 2.3

  • The method of obtaining the element there are two types, one is to obtain and removed from the array, one element not only obtaining removed
  • get out of class for not calling for the removal of poll

3. A few notes

  • Note: E remove the call is removeFirst

  • Note: boolean offer call is offerLast

  • Note: boolean add call is addLast

  • Note: E poll call is pollFirst

  • Note: E element is called getFirst

  • Note: E peek call is peekFirst

  • Note: push the call is: addFirst

  • Note: pop call is removeFirst

  • See above may correspond to the source code can be very simple.

Guess you like

Origin juejin.im/post/5e00b06351882512416a6e51