Arraylist 和 Linkedlist 的区别

本文详细对比了ArrayList与LinkedList两种Java集合类的区别。ArrayList基于动态数组实现,适合随机访问和修改操作;而LinkedList基于链表实现,适用于频繁的插入和删除操作。两者都不是线程安全的,但可通过Collections.synchronizedList方法实现同步。

首先我们摘录JDK的 java.util包中对于这两个类的部分定义

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     */
    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.
     */
    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

    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    private int size;

    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    transient int size = 0;

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    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.
     */
    public LinkedList() {
    }
  }

从此可以看到两者都实现了List接口,而且都不是线程安全的。

两者的区别如下:

1.从底层实现上来说:ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。
2.对于随机访问和修改操作,ArrayList性能优于LinkedList,因为LinkedList如果要查找某个元素,每次都是从否开始查找;而对于随机插入和删除操作,LinkedList性能优于ArrayList,因为ArrayList的插入和删除操作要移动后面的数据。

因为两个类都不是线程安全的,所以当有多个线程要同时获得类的实例的时候,可以通过Collections的静态方法,在外部给实例对象进行同步:
List list = Collections.synchronizedList(new ArrayList(…));
List list = Collections.synchronizedList(new LinkedList(…));

好了,现在再P一段连个类常用的方法吧,摘自API:

boolean add(E e)
Appends the specified element to the end of this list.
void    add(int index, E element)
Inserts the specified element at the specified position in this list.
boolean contains(Object o)
Returns true if this list contains the specified element.
E   get(int index)
Returns the element at the specified position in this list.
boolean isEmpty()
Returns true if this list contains no elements.
E   remove(int index)
Removes the element at the specified position in this list.
boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
E   set(int index, E element)
Replaces the element at the specified position in this list with the specified element.
int size()
Returns the number of elements in this list.
### Java中ArrayListLinkedList区别 #### 1. **底层数据结构** - `ArrayList` 是基于动态数组实现的,其内部维护了一个对象数组。当容量不足时,会自动扩容以容纳更多元素[^1]。 - `LinkedList` 则是一个双向链表结构,每个节点包含前驱指针、后继指针以及当前存储的数据项。这种设计使得它更适合频繁插入删除的操作[^2]。 #### 2. **性能对比** ##### 2.1 随机访问 - 对于随机访问(通过索引获取元素),`ArrayList` 提供 O(1) 时间复杂度的支持,因为它可以直接计算目标位置并返回相应值[^3]。 - 而 `LinkedList` 的随机访问效率较低,达到某个指定索引处的时间复杂度为 O(n),因为需要从头或者尾遍历至该位置[^4]。 ##### 2.2 插入删除 - 当涉及到中间位置上的插入或移除操作时,`ArrayList` 可能较慢,原因是这些动作可能引发大量后续元素向左或右整体平移的过程,平均时间复杂度接近 O(n)[^5]。 - 相反,在相同情况下,由于 `LinkedList` 不必调整其他部分仅需改变几个链接关系即可完成任务,因此它的此类操作通常更快一些,具有常数级即 O(1) 的理想情况下的表现[^6]。 ##### 2.3 内存占用 - 尽管如此,值得注意的是尽管单次增删更高效但每增加一个新项目到 `LinkedList` 中都需要额外分配两个引用空间用于保存前后连接信息,这导致总体内存消耗大于同等长度下简单连续排列形式呈现出来的 `ArrayList` 结构[^7]。 #### 3. **使用场景** ##### 适合使用 ArrayList 的场景: - 如果应用程序主要涉及大量的读取操作而非写入/修改,则应优先考虑采用 `ArrayList` ,因其提供了快速定位任意元素的能力[^8]。 ##### 适合使用 LinkedList 的场景: - 若业务逻辑里存在许多顺序无关紧要却经常发生的变化比如队列模拟等问题解决方案构建过程中的临时缓冲区管理等方面可以选用 `LinkedList` 来优化运行速度减少不必要的位移开销从而提升整个系统的响应速率[^9]。 ```java // ArrayList 示例代码 import java.util.ArrayList; public class Main { public static void main(String[] args){ ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("Element"); String element = arrayList.get(0); // 快速访问第一个元素 } } // LinkedList 示例代码 import java.util.LinkedList; public class Main { public static void main(String[] args){ LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.addFirst(1); linkedList.removeLast(); // 效率高的首尾操作 Integer firstElement = linkedList.getFirst(); } } ``` #### 总结 综上所述,虽然两者都实现了相同的接口功能相似之处很多,但在具体应用层面还是各有千秋——前者凭借紧凑布局带来更好的缓存命中率进而提高迭代器遍历时的整体效能;后者依靠灵活机动特性适应那些侧重局部变动处理需求的应用环境之中[^10]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值