ArrayList与LinkedList区别源码分析

ArrayList与LinkedList

数组和链表的区别

  • 数组:
    处理一组数据类型相同的数据。但是不允许动态定义数组的大小,即在使用数组之前必须确定数组的大小。这样数组中的有些空间可能不被使用,从而造成内存空间的浪费。当数据增加时,可能超出原先定义的元素个数,造成数组越界。数组插入删除时需要移动其他数据项。但是查询方便。
    数组从栈中分配空间,对于程序员方便快速,数组无需初始化,因为数组元素在内存的栈区,系统自动申请空间。但是自由度小。数组元素在内存中连续

  • 链表:
    链表动态的进行存储分配,可以适应数据动态地增减的情况,且可以方便地插入、删除数据项。链表插入和删除时,只需要改变个别元素之间的关系,这大大提高了链表的删除和插入的速度。查询时需要从前往后遍历。
    链表从堆中分配空间,自由度大,但是申请管理比较麻烦,链表的结点元素在内存的堆区,每个元素须手动申请空间。链表在内存中不一定连续。

ArrayList

简介

这里写图片描述

/**
     * Default initial capacity.
     * ArrayList 默认的数组容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     *  用于空实例的共享空数组实例
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     * 另一个共享空数组实例,用的不多,用于区别上面的EMPTY_ELEMENTDATA
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     * ArrayList底层的容器  
     */
    // Android-note: Also accessed from java.util.Collections
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 当前存放了多少个元素   并非数组大小
     */
    private int size;

ArrayList是基于动态数组的数据结构。实现了list接口,是以数组的方式实现的。所谓动态数组是这样实现的,如果没有指定数组的大小,则申请默认大小为10 的数组,当元素个数增加,数据无法存储时,系统会另外申请一个长度为当前长度的1.5倍的数组,然后把之前的数据拷贝到新建的数组中。
数组的特征是可以使用索引的方式来快速定位对象的位置。适合读取数据。

ArrayList源码分析

  • 添加
/**
* 添加指定元素到末尾
*/
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

  //扩容
 private void grow(int minCapacity) {
        // overflow-conscious code
        //1. 记录之前的数组长度
        int oldCapacity = elementData.length;
        //2. 新数组的大小=老数组大小+老数组大小的一半
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //3. 判断上面的扩容之后的大小newCapacity是否够装minCapacity个元素
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
              //4.判断新数组容量是否大于最大值
    //如果新数组容量比最大值(Integer.MAX_VALUE - 8)还大,那么交给hugeCapacity()去处理,该抛异常则抛异常
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        //5. 复制数组,注意,这里是浅复制
        elementData = Arrays.copyOf(elementData, newCapacity);

private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

思路:
1.首先判断添加一个元素是否会导致数组溢出
2.判断是否溢出:如果原数组为空,那么第一次添加数组时会给数组一个默认大小10,接着判断是否溢出,如果溢出则去扩容,扩容规则:新数组是原数组大小的1.5倍,最后通过Arrays.copyOf()去浅复制
3.添加元素到末尾

  • 获取
/**
 * 返回指定位置处元素
*/
 public E get(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        return (E) elementData[index];
    }

思路:通过下标获得数组中的元素

  • 移除
public E remove(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        modCount++;
        E oldValue = (E) 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;
    }
public static native void arraycopy (Object src,//源数组
                             int srcPos,//源数组要复制的起始位置
                             Object dest,//目的数组
                             int destPos,//目的数组放置的起始位置
                             int length)//复制的长度

思路:数组自己复制自己,跳过需要移除的下标元素

  • 修改
public E set(int index, E element) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));

        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }

思路:替换index索引处的元素为element,可能会抛出IndexOutOfBoundsException.这里比较简单,就是将index处的元素替换成element

ArrayList总结

1.底层是object数组存数据
2.扩容机制:默认大小是10,扩容是扩容到之前的1.5倍大小,每次扩容是将原数组中的数据复制到新的数组中
3.添加:如果是添加到数组的指定位置,那么可能会挪动大量的数组元素,并且可能会触发扩容机制;如果是添加到末尾的话,那么只可能触发扩容机制.
4.删除:如果是删除数组指定位置的元素,那么可能会挪动大量的数组元素;如果是删除末尾元素的话,那么代价是最小的. ArrayList里面的删除元素,其实是将该元素置为null.
5.查询和改某个位置的元素是非常快的( O(1) ).

浅复制与深复制概念

  • 浅复制
    浅复制实例和原始实例的引用类型引用同一个对象;
  • 深复制
    深复制实例和原始实例的引用类型引用不同对象。

LinkedList

简介

这里写图片描述
LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。有关索引的操作可能从链表头开始遍历到链表尾部,也可能从尾部遍历到链表头部,这取决于看索引更靠近哪一端。
LinkedList 实现 List 接口,能对它进行队列操作。
LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。
LinkedList 是非同步的。

LinkedList源码分析

内部结构

LinkedList内部是一个双端链表的结构
关键字transient 序列化对象的时候,这个属性就不会序列化到指定的目的地中

    transient int size = 0;

    /**
     * Pointer to first node. 指向链表头部
     */
    transient Node<E> first;

    /**
     * Pointer to last node.指向链表尾部
     */
    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;
        }
    }

构造函数

默认构造方法是空的,什么都没做,表示初始化的时候size为0,first和last的节点都为空:

/**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

带Collection值得对象作为入参的构造函数


    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();//调用默认的无参构造函数
        addAll(c);
    }

添加元素

  • add(E e) 添加到链表末尾
/**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
     /**
     * Links e as last element.
     */
    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;//将之前的尾结点的next指针指向新的结点
        //增加链表长度
        size++;
        modCount++;
    }

add(E e)添加成功返回true,添加失败返回false.分配内存空间不是必须是连续的,所以只要是还能给它分配空间,就不会添加失败.当空间不够分配时(内存溢出),会抛出OutOfMemory.

  • addLast(E e) 添加元素到末尾
    内部实现和add(E e)一样
 /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #add}.
     *
     * @param e the element to add
     */
    public void addLast(E e) {
        linkLast(e);
    }
  • addFirst(E e) 添加元素到链表头部
/**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * Links e as first element.
     */
    private void linkFirst(E e) {
     //记录头结点
        final Node<E> f = first;
        //新建头结点
        final Node<E> newNode = new Node<>(null, e, f);
        //新建的结点赋值给链表的头结点
        first = newNode;
        //如果之前头结点为空
        if (f == null)
            last = newNode;//头结点=尾结点=新建的结点 (相当于空链表插入第一个元素,头结点等于尾节点)
        else //如果不为空
            f.prev = newNode;//之前头结点的 prev指针指向 新建的结点
        //增减链表长度
        size++;
        modCount++;
    }
  • add(int index, E element) 添加元素到指定位置
    可能会抛出IndexOutOfBoundsException
   /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
    //检查是否越界
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);//和 add(E e) 添加到链表末尾相同
        else
            linkBefore(element, node(index));
    }
    /**
    *检查是否越界
    */
        private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
 /**
     * Returns the (non-null) Node at the specified element index.
     * 返回指定元素索引处的(非空)节点。
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
//如果index在链表的前半部分,那么从first开始往后查找;否则,从last往前面查找
        if (index < (size >> 1)) {
        //记录第一个节点
            Node<E> x = first;
            //循环从第一个节点开始往后查,直到达到index处,返回index处元素
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
        //index在链表的后半部分,记录最后一个节点
            Node<E> x = last;
            //循环从最后一个节点开始往前查,直到达到index处,返回index处的元素
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

 /**
     * Inserts element e before non-null Node succ.
     * 在非null节点succ之前插入元素e。
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        //记录succ的前一个结点
        final Node<E> pred = succ.prev;
        //新建一个结点,前结点是pred  ,数据是e,下一个结点是succ
        final Node<E> newNode = new Node<>(pred, e, succ);
        //将新的结点赋值给 succ的前结点
        succ.prev = newNode;
        //如果之前的succ的前一个结点 pred  为空
        if (pred == null)
            first = newNode;//如果为空,那么说明succ是之前的头节点.现在新节点在succ的前面,所以新节点是头节点
        else
            pred.next = newNode;//否则,直接将succ的前一个节点pred指向新节点就可以了
        //增加链表长度
        size++;
        modCount++;
    }

总结:
首先判断插入的位置是在链表的最后还在在中间
如果是插入到链表的末尾,那么将之前的尾结点指向新的结点
如果是插入到链表中间
需要找到index 处的结点
将新结点赋值给index处结点的前一个(prev)结点
将index处结点的前一个结点的next指针指向新结点

  • 将指定集合的所有元素插入到末尾位置
  public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
     /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * @param index index at which to insert the first element
     *              from the specified collection
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        //1. 检查是否越界
        checkPositionIndex(index);
        //将插入的集合转成数组
        Object[] a = c.toArray();
        // 记录插入元素集合的个数
        int numNew = a.length;
         如果个数为0,那么插入失败,不继续执行了
        if (numNew == 0)
            return false;

        Node<E> pred, succ;// 目标索引的前一个结点,目标索引的结点
        //判断下插入的index和链表size是否相等,相等则相当于在链表末尾插入
        if (index == size) {
            succ = null;//index 处结点为null
            pred = last;// indext处前结点 为尾结点
        } else {//否则,插入中间
            succ = node(index);//找到index 处结点
            pred = succ.prev;//记录index处前一个结点
        }
        //循环将集合中所有元素连接到pred后面
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            //如果前一个是空,那么将新节点作为头结点
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;//指向新节点
                pred = newNode;
        }
        //判断succ是否为空,为空的话,那么集合的最后一个元素就是尾节点
        if (succ == null) {
            last = pred;
        } else {//非空的话,那么将succ连接到集合的最后一个元素后面
            pred.next = succ;
            succ.prev = pred;
        }
        //8. 链表长度+numNew
        size += numNew;
        modCount++;
        return true;
    }

这里写图片描述

  • offer() offerLast(E e) 添加元素到链表尾部
/**
     * Adds the specified element as the tail (last element) of this list.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Queue#offer})
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }
 /**
     * Inserts the specified element at the end of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerLast})
     * @since 1.6
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }
  • ,offerFirst(E e) 添加元素到链表头部
 /**
     * Inserts the specified element at the front of this list.
     *
     * @param e the element to insert
     * @return {@code true} (as specified by {@link Deque#offerFirst})
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

删除元素

  • E remove(),removeFirst() 移除链表第一个元素
/**
     * Retrieves and removes the head (first element) of this list.
     *移除链表第一个元素
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }
 /**
     * Removes and returns the first element from this list.
     *移除和返回 链表的第一个元素
     * @return the first element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
   /**
     * Unlinks non-null first node f.
     * 将第一个结点删掉
     */
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        //记录第一个结点的数据值
        final E element = f.item;
        //记录下一个结点
        final Node<E> next = f.next;
        //将第一个结点置空,帮助Gc 回收
        f.item = null;
        f.next = null; // help GC
        //将之前头结点的下一个结点 赋值为头结点
        first = next;
        //如果为空,则链表没有结点了,
        if (next == null)
            last = null;
        else//否则,将新节点的prev指针置为空
            next.prev = null;
         //链表长度 -1
        size--;
        modCount++;
        // 返回删除结点的数据值
        return element;
    }
/**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     */
     protected transient int modCount = 0;
  • E removeLast() 移除最后一个元素并返回
/**
     * Removes and returns the last element from this list.
     *
     * @return the last element from this list
     * @throws NoSuchElementException if this list is empty
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
 /**
     * Unlinks non-null last node l.
     * 移除链表最后一个元素
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        //记录删除结点(尾结点)的数据值
        final E element = l.item;
        //记录删除结点 (尾结点)的前结点
        final Node<E> prev = l.prev;
        //将尾结点置空,方便Gc
        l.item = null;
        l.prev = null; // help GC
        //将前结点 赋值给链表尾结点
        last = prev;
        //判断前结点是否为空
        if (prev == null)
            first = null;//如果为空,则链表没有结点了
        else
            prev.next = null;// 否则,直接将新的尾节点的next指针指向null
         //链表长度-1
        size--;
        modCount++;
        return element;
    }
  • removeFirstOccurrence(Object o) remove(Object o) 从此链表中删除第一次出现的指定元素o
/**
     * Removes the first occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     * does not contain the element, it is unchanged.
     */
public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

/**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged. 
     * /
public boolean remove(Object o) {
    //判断o是否为空
        if (o == null) {
         // 找第一个数据值为null的节点
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);//删除结点
                    return true;
                }
            }
        } else {// /非空  循环,找第一个与o的数据值相等的节点
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);//删除结点
                    return true;
                }
            }
        }
        return false;
    }

/**
     * Unlinks non-null node x.
     * 移除节点x
     */
    E unlink(Node<E> x) {
        // assert x != null;
        //1. 记录该节点数据值,前一个节点prev,后一个节点next
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;
    //判断前一个节点是否为空
        if (prev == null) {
            first = next;//为空的话,那么说明之前x节点是头节点  这时x的下一个节点成为头节点
        } else {//非空的话,将前一个节点的next指针指向x的下一个节点
            prev.next = next;
            x.prev = null; //x的prev置为null
        }

    // 判断x后一个节点是否为空
        if (next == null) {//为空的话,那么说明之前x节点是尾节点,这时x的前一个节点成为尾节点
            last = prev;
        } else {
            next.prev = prev;//为空的话,将x的下一个节点的prev指针指向prev(x的前一个节点)
            x.next = null; //x的next指针置空
        }
    //x节点数据值置空
        x.item = null;
        //链表长度-1
        size--;
        modCount++;
        return element;
    }

这里写图片描述
- E remove(int index) 移除指定位置元素

/**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     */
public E remove(int index) {
    ////检查入参是否合法/越界
        checkElementIndex(index);
        ////node(index)找到index处的节点  
        return unlink(node(index));//删除index处的结点
    }
  • removeLastOccurrence(Object o) 从此链表中删除最后一次出现的指定元素o.
/**
     * Removes the last occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     * does not contain the element, it is unchanged.
     * 遍历时是从尾节点开始往前查找的.
     */
public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
  • E poll() 获取第一个元素的同时删除第一个元素,当链表无节点时,不会报错.
/**
     * Retrieves and removes the head (first element) of this list.
     *
     * @return the head of this list, or {@code null} if this list is empty
     * @since 1.5
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
  • E pop() 获取第一个元素的同时删除第一个元素,当链表无节点时,会报错.
/**
     * Pops an element from the stack represented by this list.  In other
     * words, removes and returns the first element of this list.
     *
     * <p>This method is equivalent to {@link #removeFirst()}.
     *
     * @return the element at the front of this list (which is the top
     *         of the stack represented by this list)
     * @throws NoSuchElementException if this list is empty
     * @since 1.6
     */
    public E pop() {
        return removeFirst();
    }

修改元素

  • E set(int index, E element) 设置index处节点数据值为element
/**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
public E set(int index, E element) {
    //检查是否越界
        checkElementIndex(index);
        //找到index处节点
        Node<E> x = node(index);
        //保存该节点旧值
        E oldVal = x.item;
        //替换为新值
        x.item = element;
         //将旧值返回
        return oldVal;
    }

查询元素

  • E element() E getFirst() 获取链表第一个元素. 方法比较简单,就是将链表头节点数据值进行返回
/**
     * Retrieves, but does not remove, the head (first element) of this list.
     *
     * @return the head of this list
     * @throws NoSuchElementException if this list is empty
     * @since 1.5
     */
    public E element() {
        return getFirst();
    }
/**
     * Returns the first element in this list.
     *
     * @return the first element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
  • E getLast() 获取链表最后一个元素. 非常简单,就是将last的数据值返回
 /**
     * Returns the last element in this list.
     *
     * @return the last element in this list
     * @throws NoSuchElementException if this list is empty
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
  • E get(int index) 获取指定索引处元素. 就是通过node(index)找到index索引处节点,然后返回其数据值
/**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

ArrayList与LinkedList使用场景

对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针。
对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据。

猜你喜欢

转载自blog.csdn.net/luyuqin0115/article/details/80395694