ArrayList&LinkedList 源码分析

💟这里是CS大白话专场,让枯燥的学习变得有趣!

💟没有对象不要怕,我们new一个出来,每天对ta说不尽情话!

💟好记性不如烂键盘,自己总结不如收藏别人!

ArrayList

package com.jodie.list;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jodie
 * @date 2023/5/25-19:39
 */
public class array {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("aaa");
    }
}

💌 进入 ArrayList 可以发现底层数组为 elementData,若使用空参构建,则创建长度为0的数组。


    /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 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; // 默认是0

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

💌 调用 add() 方法才会触发扩容机制,简单来说就是添加第一个元素的时候扩容到10,然后添加到第11个元素时扩容到15(若调用 addAll() 方法则在扩容1.5倍后的容量旧容量加添加的元素之和之间取最大值进行扩容):

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++; //数组被修改次数

        // overflow-conscious code
        if (minCapacity - elementData.length > 0) // 数组空间够用则不用扩容
            grow(minCapacity);  //扩容
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            // 如果是空参构造,在添加第一个元素时扩容到10
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        //若不是空参则添加多少扩容多少
        return minCapacity;
    }

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);  //扩容1.5倍
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;  // 首次扩容到10
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        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;
    }

LinkedList

    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;
        }
    }

    /**
     * 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;  //左节点的右节点为新节点
        size++;
        modCount++;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ArrayList的时间复杂度分析主要包括插入、删除和访问操作的时间复杂度。 对于插入和删除操作,如果是在数组的末尾进行操作,时间复杂度为O(1),因为只需要将元素添加到数组的末尾或者从数组的末尾删除元素。然而,如果是在数组的中间进行插入或删除操作,需要将后面的元素向后移动或者向前移动,所以时间复杂度为O(n),其中n是数组的长度。 对于访问操作,由于ArrayList底层使用数组实现,可以直接通过索引访问数组中的元素,所以时间复杂度为O(1)。 另外,当ArrayList需要扩容时,会创建一个新的数组,并将原有数组中的元素拷贝到新数组中。根据引用中的介绍,ArrayList的扩容时间复杂度为O(n),其中n是数组的长度。 综上所述,ArrayList的插入和删除操作的时间复杂度为O(n),访问操作的时间复杂度为O(1),扩容操作的时间复杂度为O(n)。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [算法 | Java中ArrayList扩容时时间复杂度是多少?](https://blog.csdn.net/BASK2311/article/details/128464628)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [[集合]ArrayList及LinkedList码和时间复杂度](https://blog.csdn.net/weixin_39552097/article/details/120913160)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值