Java基础--初步分析ArrayList源码

本文介绍了Java集合容器ArrayList,它继承AbstractList,实现多个接口,底层基于数组存储,支持null,查询效率高。还介绍了其三种构造方法,以及扩容机制,每次add元素时会检查容量,不够则扩容为原容量的1.5倍。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

ArrayList作为Java集合容器,在我们的开发过程中是非常常见的。
ArrayList继承了AbstractList,实现了List、RandomAccess、Cloneable以及Serializable接口,支持快速访问、复制以及序列化。
ArrayList底层是基于数组的存储结构,支持null,可以通过索引进行随机访问,所以ArrayList的查询效率非常高。
但是数组的长度是固定的,默认长度是10,当ArrayList里的元素增加到一定数量时会进行扩容,生成新的数组并把之前的数组引用指向新的数组。

部分源码

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;

构造方法

ArrayList支持三种构造方法
1、ArrayList(int initialCapacity)–指定初始化创建ArrayList的大小
2、ArrayList()–默认构造方法
3、ArrayList(Collection<? extends E> c)–传入一个Collection对象,内部通过Arrays.copyOf()转换成ArrayList

扩容

ArrayList每次add元素的时候都会检查数组容量够不够,如果容量不够的话会进行扩容操作,
newCapacity = oldCapacity + (oldCapacity >> 1);
扩容之后的容量大小为之前的1.5倍

持续更新中…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qrainly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值