ArrayList源码浅析

简介: Java中List是一个必须要掌握的基础知识,List是一个接口,实现List接口的基础类有很多,其中最具有代表性的两个:ArrayList和LinkedList。

Java中List是一个必须要掌握的基础知识,List是一个接口,实现List接口的基础类有很多,其中最具有代表性的两个:ArrayList和LinkedList。


01变量


ArrayList是一个底层基于数组实现动态大小扩容的数据结构,快速访问、可复制、序列化的。继承自 AbstractList,实现了 List 接口。写代码时,我们经常用到这个数据结构来做大数据量的访问和(程序)缓存存储等。


/**     * Default initial capacity.     * 默认初始容量10     */    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用来表示一个域不是该对象序行化的一部分     */    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的基本变量组成,private int size; 和 transient Object[] elementData; 则是ArrayList的成员变量。


02构造函数


2.1 无参构造函数


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

注释说初始给数组赋值空间大小时为10的list集合,当第一次添加元素时即给数组容量扩大了10倍。


2.2 带初始容量大小的构造函数


/**     * 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);        }    }


当initialCapacity=0时,则把EMPTY_ELEMENTDATA赋值给 elementData;当initialCapacity大于0时,初始化为一个大小为initialCapacity的Object数组,并赋值给elementData。否则,抛出异常“非法的大小”;即初始容量大小大于等于0.


03操作方法


3.1 add()添加方法

往数组中添加一个元素e,数组容量大小增加一。


/**     * 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 static int calculateCapacity(Object[] elementData, int minCapacity) {        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {            return Math.max(DEFAULT_CAPACITY, minCapacity);        }        return minCapacity;    }

每次添加元素到集合中时都会先确认下集合容量大小,随后再增加1。


3.2 remove()移除方法

分2个,一个是移除元素在数组中的位置的方法。一个是移除元素的方法。


/**     * Removes the element at the specified position in this list.     * Shifts any subsequent elements to the left (subtracts one from their     * indices).     *     * @param index the index of the element to be removed     * @return the element that was removed from the list     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public E remove(int index) {        rangeCheck(index);
        modCount++;        E oldValue = 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;    }
    /**     * Removes the first occurrence of the specified element from this list,     * if it is present.  If the list does not contain the element, it is     * unchanged.  More formally, removes the element with the lowest index     * <tt>i</tt> such that     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>     * (if such an element exists).  Returns <tt>true</tt> if this list     * contained the specified element (or equivalently, if this list     * changed as a result of the call).     *     * @param o element to be removed from this list, if present     * @return <tt>true</tt> if this list contained the specified element     */    public boolean remove(Object o) {        if (o == null) {            for (int index = 0; index < size; index++)                if (elementData[index] == null) {                    fastRemove(index);                    return true;                }        } else {            for (int index = 0; index < size; index++)                if (o.equals(elementData[index])) {                    fastRemove(index);                    return true;                }        }        return false;    }
    /*     * Private remove method that skips bounds checking and does not     * return the value removed.     */    private void fastRemove(int index) {        modCount++;        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    }

可以很快速的理解:移除元素在数组中位置的方法是,把该元素在数组的中的下标位置对应的元素移除。先检查对应入参的下标位置是否超出数组的大小限制(数组溢出),然后把该元素移除,再把数组大小减一。

移除元素,当元素为空的时候,匹配数组中是否有空的元素,有则移除,数组大小减一。元素不为空的时候,循环数组元素,匹配元素后,移除数组,数组大小减一。


3.3 isEmpty()和size()等常用函数方法


/**     * Returns the number of elements in this list.     *     * @return the number of elements in this list     */    public int size() {        return size;    }
    /**     * Returns <tt>true</tt> if this list contains no elements.     *     * @return <tt>true</tt> if this list contains no elements     */    public boolean isEmpty() {        return size == 0;    }

在进行数组的大小比较和判断操作时用的一些基本方法。

ArrayList 底层基于数组实现容量大小动态可变。扩容机制为首先扩容为原始容量的 1.5 倍。如果1.5倍太小的话,则将我们所需的容量大小赋值给 newCapacity,如果1.5倍太大或者我们需要的容量太大,那就直接拿newCapacity=(minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE 来扩容。

相关文章
|
安全 Android开发
Android 预置可卸载分区接收不到任何广播问题分析和解决
Android 预置可卸载分区接收不到任何广播问题分析和解决
1201 0
|
9月前
|
人工智能 数据挖掘 Linux
一个人就是一支队伍:阿里云/本地部署OpenClaw多Agent协作实战、配置免费大模型API及避坑指南
在AI工具普及的今天,仅靠单个Agent处理所有任务,会面临上下文混乱、专业度不足、重复解释背景等问题。OpenClaw提供了一套完整的多Agent协作架构,让你可以**一人管理一支AI团队**:研究、写作、设计、开发、运营、数据分析等角色各司其职、独立记忆、互不干扰,实现零沟通成本、高效率并行执行。从“自己动手”升级为“管理AI团队”,是新一代AI使用者的核心能力。
989 1
|
编解码 语音技术 数据安全/隐私保护
企业微信协议语音链路的技术实现
企业微信移动端语音采用0x0602指令,通过长连接传输Silk压缩流,降低30%首包延迟。协议含固定帧头与TLV结构,支持AES加密与实时解码,网关可透明转码对接ASR系统,整体延迟约8ms,CPU占用低。
695 0
|
6月前
|
Kubernetes Ubuntu 网络协议
|
10月前
|
机器学习/深度学习 存储 人工智能
让 AI 智能体学会自我进化:Agent Lightning 实战入门
Agent Lightning 是一个框架无关的强化学习包装层,赋能现有AI智能体实现在线持续学习。它解耦执行与训练,支持LangChain/AutoGen等任意框架,通过VERL算法解决稀疏奖励难题,让智能体从运行反馈中自动优化提示词与策略。
1013 5
让 AI 智能体学会自我进化:Agent Lightning 实战入门
|
9月前
|
人工智能 自然语言处理 供应链
【最新】阿里云ClawHub Skill扫描:3万个AI Agent技能中的安全度量
阿里云扫描3万+AI Skill,发现AI检测引擎可识别80%+威胁,远高于传统引擎。
2944 3
|
存储 Prometheus 监控
136_生产监控:Prometheus集成 - 设置警报与指标选择与LLM部署监控最佳实践
在大语言模型(LLM)部署的生产环境中,有效的监控系统是确保服务稳定性、可靠性和性能的关键。随着LLM模型规模的不断扩大和应用场景的日益复杂,传统的监控手段已难以满足需求。Prometheus作为当前最流行的开源监控系统之一,凭借其强大的时序数据收集、查询和告警能力,已成为LLM部署监控的首选工具。
1113 6
|
JavaScript 小程序 API
UniApp X:鸿蒙原生开发的机会与DCloud的崛起之路·优雅草卓伊凡
UniApp X:鸿蒙原生开发的机会与DCloud的崛起之路·优雅草卓伊凡
1083 12
UniApp X:鸿蒙原生开发的机会与DCloud的崛起之路·优雅草卓伊凡
|
JSON 安全 API
淘宝天猫上货API接口技术指南
本文介绍淘宝天猫上货API,详解其RESTful接口原理、认证流程及Python调用示例。涵盖商品添加、签名生成、响应处理,并提供代码实现与最佳实践,助力开发者高效实现自动化批量上架。
1450 3
|
机器学习/深度学习 数据采集 监控
107_DPO:直接偏好优化
在大型语言模型(LLM)的发展历程中,如何让模型输出与人类偏好保持一致一直是研究的核心挑战。从早期的监督微调(SFT)到基于人类反馈的强化学习(RLHF),再到如今的直接偏好优化(DPO),对齐技术经历了显著的迭代与创新。
1923 1