LinkedList与ArrayList的get(int index)方法区别

LinkedList与ArrayList的get(int index)方法区别

首先我们看看源码

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

private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }


//ArrayList
public E get(int index) {
        Objects.checkIndex(index, size);
        return elementData(index);
    }

E elementData(int index) {
        return (E) elementData[index];
    }

transient Object[] elementData;

从源码中我们可以看到,ArrayList是在动态维护一个Object类型的elementData数组,使用get()方法获取元素时,相当于在数组中以元素下标获得元素。而LinkedList是在动态维护一个元素类型为Node的链表,当使用get()方法时,只能从头部或尾部开始访问,(通过size来决定开始位置),然后一个个开始遍历直到该方法获取到index的元素(比如说从头开始,用一个count计数,count = 0,每次访问一个元素count就+1,直到count == index时,输出这个元素。或者从尾开始,count = size - 1,边遍历count边减少,然后直到count == index ,输出这个元素)

因此,LinkedList的get(int index)方法会比ArrayList的get(int index)方法效率低。

原文地址:https://www.cnblogs.com/ZJHqs/p/15026052.html