ArrayList和LinkedList区别详解(从源码角度入手,版本:jdk1.8)

一、ArrayList

底层使用数组来实现该容器,当我们使用其查找某个数据时,效率高,而在添加,删除某数据时,效率低下
首先,我们来看看其源码(与后面LinkedList源码搭配来看,效果更佳)
get方法:

public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

这个是get方法的源码,其中rangeCheck(index)方法是判断该传入的索引位置是否超出容器容量,如果没有超过,则执行elementData()方法,而该方法源码如下:

@SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

可以看到,在底层实现中,维护了一个elementData数组,通过数组的下标,我们可以很快的找到该位置的元素。
其时间复杂度为O(1)

那么底层数组又是如何根据下标快速地找到元素的呢?

其实在内存中,数组的数据连续存放,数据长度固定,这样知道数组开头位置和偏移量就可以直接算出数据地址。

add方法:

public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

可以看到在add方法中,首先进行index的边界检查,是否越界,然后调用方法ensureCapacityInternal(size + 1); 将原数组+1扩容,而后调用 System.arraycopy(elementData, index, elementData, index + 1, size - index);方法将原数组从index开始依次向后移动1位,最后在数组的index位置加入某个元素,完成添加。其时间复杂度为O(n)

另:有关System.arraycopy和深拷贝和浅拷贝的相关知识,欢迎浏览此文章:

https://blog.csdn.net/weixin_43896829/article/details/105359599

remove方法:

public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

该方法的分析和add方法类似,交给读者自行分析体会。时间复杂度为O(n)

二、LinkedList

底层使用链表来实现该容器,与ArrayList相反,该容器在添加,删除某元素时,效率高,而在查找某元素时,效率低,同样,我们通过源码来分析他的原因:
get方法

public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

其中node().item源码如下

Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

可以看到,在LinkList中维护了一个Node泛型,该方法先通过将index和size/2相比较,若小于,则从头开始向后遍历,如果大于,则从尾指针向前开始遍历,从而获得元素是否处于该位置,这样一来,便可以理解为何LinkedList在查找时效率低下的问题。其时间复杂度为O(n/2)=O(n)

add方法:

public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
 void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

首先,检查index的位置是否不合法。然后如果index等于size,调用linkLast函数,插入链表的最后,如果index不等于size,则先用node函数找到该索引的位置(时间复杂度仍为O(n)),然后将链表插入其中,并调整相关前后节点的引用。所以其时间复杂度为O(n)

remove方法:

public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }

同样,remove方法过程与add类似,时间复杂度为O(n),源码如上,请读者自行分析

总结:
可以看到虽然在查找和删除方面ArrayList和LinkedList的时间复杂度都为O(n),但是由于数组需要进行容量需要进行缩小,并且元素需要做相应的移位,从这一点上来讲LinkedList在插入,删除元素是优于ArrayList的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值