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 来扩容。

相关文章
|
存储 自然语言处理 索引
ES分词器使用说明(analyzer)
本文章主要介绍了分词器的配置方法,以及分词器的优先级,同时配置了多个维度的分词器,哪一个分词器会生效,当出现分词结果不符合预期的时候,可以通过这个本文档内容进行梳理和排查。
2598 0
|
前端开发 JavaScript
百度统计失效,referrer背锅了
前段时间遇到一个问题,就是我的个人网站需要接入第三方百度统计,因为我的文章图片有来自第三方微信后台上传的文章,所以使用&lt;meta name=&quot;referrer&quot; content=&quot;no-referrer&quot;&gt;解决图片访问403的问题,但是此时这个导致我百度统计失效了,于是去查询了一下referrer这个特性。
531 0
百度统计失效,referrer背锅了
|
9月前
|
XML Java 数据格式
Spring Core核心类库的功能与应用实践分析
【12月更文挑战第1天】大家好,今天我们来聊聊Spring Core这个强大的核心类库。Spring Core作为Spring框架的基础,提供了控制反转(IOC)和依赖注入(DI)等核心功能,以及企业级功能,如JNDI和定时任务等。通过本文,我们将从概述、功能点、背景、业务点、底层原理等多个方面深入剖析Spring Core,并通过多个Java示例展示其应用实践,同时指出对应实践的优缺点。
141 14
|
Kubernetes Cloud Native 持续交付
云原生架构的核心组成部分通常包括容器化(如Docker)、容器编排(如Kubernetes)、微服务架构、服务网格、持续集成/持续部署(CI/CD)、自动化运维(如Prometheus监控和Grafana可视化)等。
云原生架构的核心组成部分通常包括容器化(如Docker)、容器编排(如Kubernetes)、微服务架构、服务网格、持续集成/持续部署(CI/CD)、自动化运维(如Prometheus监控和Grafana可视化)等。
|
10月前
|
缓存 算法 前端开发
如何降低 SPA 单页面应用的内存占用
单页面应用(SPA)由于其良好的用户体验而被广泛使用,但随着应用复杂度的增加,内存占用问题日益突出。本文将介绍几种有效降低SPA内存占用的方法,包括代码分割、懒加载、状态管理优化等技术,帮助开发者提升应用性能。
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?
283 0
|
前端开发
vue3 【提效】使用 CSS 框架 UnoCSS 实用教程
vue3 【提效】使用 CSS 框架 UnoCSS 实用教程
616 1
|
存储 安全 测试技术
【Docker项目实战】使用Docker部署JmalCloud个人网盘
【4月更文挑战第15天】使用Docker部署JmalCloud个人网盘
697 4
|
存储 消息中间件 监控
ELK日志收集系统集群实验(5.5.0版)
ELK是指Elasticsearch、Logstash和Kibana的组合。它们是一套开源的日志收集、存储、搜索和可视化系统,常用于集中管理和分析日志数据。
232 0
|
监控 数据可视化 前端开发
一个.NetCore前后端分离、模块化、插件式的通用框架
一个.NetCore前后端分离、模块化、插件式的通用框架
363 0

热门文章

最新文章