zoukankan      html  css  js  c++  java
  • ArrayList与LinkedList

    ArrayList和LinkedList都是实现了List接口的容器类,用于存储一些列引用对象。只观察功能,它们都可以对元素进行增删改查操作,那它们的区别有哪些呢?下面来说一下

    实现原理

    ArrayList是基于数组结构实现的,LinkedList是基于链表结构实现的。

    ArrayList的源码:

      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.
         */
        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.
         */
        transient Object[] elementData; // non-private to simplify nested class access

    LinkedList的源码:

    transient Node<E> first;
    
        /**
         * Pointer to last node.
         * Invariant: (first == null && last == null) ||
         *            (last.next == null && last.item != null)
         */
        transient Node<E> last;
    
        /**
         * Constructs an empty list.
         */

    Get()方法获取指定元素

    ArrayList集合中使用get()方法获取元素是通过直接读取下标实现的,复杂度为O(1)。而LinkedList中get()方法需要从头结点开始依次遍历,复杂度为O(n)

    remove(index)方法删除元素

    ArrayList中被删除的元素后面的元素需要逐个移动,复杂度为O(n)。LinkedList直接指针指向操作,复杂度O(1)

    存储空间

    ArrayList在使用的时候默认的初始化对象数组的大小长度为10,如果空间不足则会采用2倍的形式进行容量的扩充,如果保存大数据量的时候有可能造成垃圾的产生和性能的下降,但是这个时候可以使用LinkedList保存

    应用场景

    ArrayList使用在查询比较多,但是插入和删除比较少的情况,而LinkedList用在查询比较少而插入删除比较多的情况

  • 相关阅读:
    P4715 【深基16.例1】淘汰赛
    P4913 【深基16.例3】二叉树深度
    P1478 陶陶摘苹果(升级版)
    P1223 排队接水
    【深基12.例1】部分背包问题
    全排列和组合
    P1036 选数
    100——第25例
    100——第24例
    100——第23例
  • 原文地址:https://www.cnblogs.com/wulianjie/p/12393126.html
Copyright © 2011-2022 走看看