ArrayDeque的数据结构(jdk8)

一个双向队列的结构分析,

    //添加到队首
    public void addFirst(E e) {
        if (e == null)
            throw new NullPointerException();
        //head从队尾依次往前
        elements[head = (head - 1) & (elements.length - 1)] = e;
        //如果中途碰见tail指针了,就证明满了,要扩容
        if (head == tail)
            doubleCapacity();
    }

    public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        //直接赋值到尾指针处
        elements[tail] = e;
        //尾指针+1,如果碰见head指针了,就证明满了,要扩容
        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
            doubleCapacity();
    }

    private void doubleCapacity() {
        //断言 一定是head指针和tail指针相遇了
        assert head == tail;
        int p = head;
        int n = elements.length;
        //分界点,左面是队尾元素,右侧是队首元素
        int r = n - p; // number of elements to the right of p
        //当前容量*2
        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;
    }

    
    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
        //指针往后+1
        head = (h + 1) & (elements.length - 1);
        return result;
    }
    
    public E getFirst() {
        @SuppressWarnings("unchecked")
        //直接返回队首元素,不清空
        E result = (E) elements[head];
        if (result == null)
            throw new NoSuchElementException();
        return result;
    }

    //和getFirst一样,只是不需要校验为null
    public E peekFirst() {
        // elements[head] is null if deque empty
        return (E) elements[head];
    }


posted @ 2019-10-25 12:59  六月过半  阅读(205)  评论(0编辑  收藏  举报