java ArrayList 和 LinkedList 源码解析比较

ArrayList 的底层数据结构是 数组

在做插入时如果 数组长度不够 就要扩容 ,按照1.5的比例扩容的,扩容需要重新创建数组,比较慢

//这就是 ArrayList真正存放 对象的地方
    	private transient Object[] elementData;
	private void grow(int minCapacity) {
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }


//插入和删除都很简单,很快 ,

Linked的数据结构,这是它的内部类,也就是每个对象存在这个弄得里面 

transient Node<E> first;

    /**
     * Pointer to last node.
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;
    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }


比较ArrayList和LinkedList的  优缺点

ArrayList 根据index查询得到对象速度很快,因为是数组,插入和删除 就比较慢了每次都要检查容量,需要占用的内存也比较大

LinkedList采用链表的方式 ,一个接着另一个的方式,根据index查询相对较慢,要从头开始,插入,删除速度很快



猜你喜欢

转载自blog.csdn.net/hyz792901324/article/details/52935164