• 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];
        }
    
    
    
  • 相关阅读:
    no-useless-call (Rules) – Eslint 中文开发手册
    Java 8 Stream
    CSS3 ,checked 选择器
    MySQL 数据类型
    _Alignas (C keywords) – C 中文开发手册
    C 库函数 – modf()
    JavaScript E 属性
    SyntaxError.prototype (Errors) – JavaScript 中文开发手册
    swagger和openAPI: 上传文件
    Java中HashMap的putAll()方法: HashMap.putAll()
  • 原文地址:https://www.cnblogs.com/june777/p/11737453.html
Copyright © 2020-2023  润新知