ArrayList源码解析(JDK8)

news2024/9/17 8:35:04

文章目录

  • 一、ArrayList继承体系
  • 二、ArrayList属性
  • 三、构造方法
    • 1、ArrayList(int initialCapacity)
    • 2、ArrayList()
    • 3、ArrayList(Collection<? extends E> c)
  • 四、ArrayList 相关操作方法
    • 1、add(E e)
    • 2、add(int index, E element)
    • 3、addAll(Collection<? extends E> c)
    • 4、get(int index)
    • 5、remove(int index)
    • 6、remove(Object o)


加油,不要过度焦虑♪(^∇^*)

一、ArrayList继承体系

ArrayList又称动态数组,底层是基于数组实现的List,与数组的区别在于,它具备动态扩展能力,从源码看一看ArrayList继承了哪些类?实现了哪些类?

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

可以看出,ArrayList实现了List、RandomAccess、Cloneable、Serializable

  • 实现List,具备基本的遍历、删除、添加等操作
  • 实现RandomAccess,支持快速随机访问
  • 实现Cloneable,支持对象被克隆
  • 实现Serializable,支持被序列化

继承体系图:

在这里插入图片描述


二、ArrayList属性

    private static final int DEFAULT_CAPACITY = 10;
    
    private static final Object[] EMPTY_ELEMENTDATA = {};
    
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
    transient Object[] elementData; 
    
    private int size;
  • DEFAULT_CAPACITY:集合的默认容量,默认为10,通过new ArrayList()空参构造器创建实例时的默认容量是10。
  • EMPTY_ELEMENTDATA:空数组,通过new ArrayList(0)创建List集合实例时用的是这个空数组。
  • DEFAULTCAPACITY_EMPTY_ELEMENTDATA:默认容量空数组,这种是通过new ArrayList()无参构造方法创建集合时用的是这个空数组,与EMPTY_ELEMENTDATA的区别是在添加第一个元素时使用这个空数组的会初始化为DEFAULT_CAPACITY(10)个元素。
  • elementData:存储数据元素的数组,使用transient修饰,该字段不被序列化。
  • size:存储数据元素的个数,elementData数组的长度并不是存储数据元素的个数。

三、构造方法

1、ArrayList(int initialCapacity)

    /**
     * Constructs an empty list with the specified initial capacity.
     * 构造具有指定初始容量的空数组
     * @param  initialCapacity  the initial capacity of the list
     * 参数initialCapacity是初始容量
     * @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) {
        	//这就是EMPTY_ELEMENTDATA
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

2、ArrayList()

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

3、ArrayList(Collection<? extends E> c)

    /**
     * 构造一个含有具体元素集合的list,按照集合迭代的顺序返回
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *	//参数c的元素放入list中
     * @param c the collection whose elements are to be placed into this list
     * //如果指定的集合为null,则抛出空指针异常
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c) {
    	// 把c转化为数组
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
           // 如果elementData类型不是Object
            if (elementData.getClass() != Object[].class)
            	//则重新拷贝为Object类型
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 用空数组代替
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

四、ArrayList 相关操作方法

1、add(E e)

添加元素到末尾,平均时间复杂度为 O ( 1 ) O(1) O(1)

    /**
    	//添加指定元素到list的末尾
     * Appends the specified element to the end of this list.
     *	//元素e被添加到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) {
    	//检查是否需要扩容,minCapacity = (size + 1)
        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) {
    // 如果list={}
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
    	// 返回最大的一方,DEFAULT_CAPACITY的值为10
        return Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    return minCapacity;
}
	//
    private void ensureExplicitCapacity(int minCapacity) {
    	//记录被修改的次数
        modCount++;
        // 当存储长度大于现有的长度时,需要扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);//扩容
    }
    /**
	 *增加容量,确保它可以容纳至少最小容量参数指定的元素数
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     * // minCapacity 是最小容量
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // 先计算现有的长度
        int oldCapacity = elementData.length;
        // 扩容1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        // 如果新容量发现比需要的容量还小,则以需要的容量为准
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //如果新容量已经超过最大容量了,则使用最大容量(Integer.MAX_VALUE - 8)
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // 以新容量拷贝出来一个新数组
        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;
}

最后来分析一下执行流程:

  1. 检查是否需要扩容;
  2. 如果elementData等于DEFAULTCAPACITY_EMPTY_ELEMENTDATA(即为{})则初始化容量大小为DEFAULT_CAPACITY(10);
  3. 新容量是老容量的1.5倍(oldCapacity + (oldCapacity >> 1)),如果加了这么多容量发现比需要的容量还小,则以需要的容量为准;
  4. 创建新容量的数组并把老数组按顺序依次拷贝到新数组中;

2、add(int index, E element)

添加元素到指定位置,平均时间复杂度为 O ( n ) O(n) O(n)

 /**
     * 在list的指定位置插入指定元素,移动当前位于该位置的元素(如果有的话)和
右边的任何后续元素(向它们的索引添加1)
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     * //index为插入指定元素的索引
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
    	//检查是否越界
        rangeCheckForAdd(index);
        //检查是否需要扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //这个方法就是在index位置空出来,index后的元素向后移动
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        //在index位置插入element
        elementData[index] = element;
        size++;
    }
    private void rangeCheckForAdd(int index) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

来看看它的执行流程执行流程:

  1. 先检查索引是否越界;
  2. 然后检查是否需要扩容;
  3. 把插入索引位置后的元素都往后挪一位;
  4. 最后在插入索引位置放置插入的元素;
  5. 元素数量增1;

3、addAll(Collection<? extends E> c)

/**
     * 在list末尾增加collection集合的所有元素
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     *
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew);  // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

执行流程:

  1. 将c转换为数组;
  2. 检查minCapacity = (size + numNew)是否需要扩容;
  3. 把数组a中的元素拷贝到elementData的尾部;
  4. size +=numNew

4、get(int index)

获取指定索引位置的元素,时间复杂度为 O ( 1 ) O(1) O(1)

/**
     * 返回list中指定位置的元素
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
    	//检查是否数组下标越界
        rangeCheck(index);
        return elementData(index);
    }
    private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
	//返回数组index的值
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

执行流程:检查数组下标是否越界,不越界则返回对应数组下标值。


5、remove(int index)

删除指定索引位置的元素,时间复杂度为 O ( n ) O(n) O(n)

    /**
     * Removes the element at the specified position in this list.
     * 将所有后续元素向左移动(从它们的索引中减去1)
     * 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);
        //修改次数加1
        modCount++;
        //记录数组index下标的值,用oldValue记录下来
        E oldValue = elementData(index);
        //记录需要移动的次数
        int numMoved = size - index - 1;
        //如果要删除的元素不是list的最后一个元素
        if (numMoved > 0)
        	//则把剩余元素向前移动numMoved位
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        //将最后一个元素删除,有助于垃圾回收
        elementData[--size] = null; // clear to let GC do its work
        //返回删除的值
        return oldValue;
    }

来看看执行流程:

  1. 首先要检查索引是否越界;
  2. 然后获取指定索引位置的元素;
  3. 接着如果删除的不是最后一位,则其它元素往前移一位;
  4. 将最后一位置为null,方便垃圾回收;
  5. 最后返回删除的元素。

需要注意的是:remove的操作并未修改数组的容量!!!


6、remove(Object o)

删除指定元素值的元素,时间复杂度为 O ( n ) O(n) O(n)

   /**
     * 从此列表中删除第一个出现的指定元素(如果存在)
     * 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.  
     * 通俗来说,删除的是index最低的元素
     * 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) {
    	//如果要删除的是null值
        if (o == null) {
        	//遍历整个list
            for (int index = 0; index < size; index++)
            	//发现list存在null值
                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;
                }
        }
        //遍历的过程中都不存在o值,则返回false代表不存在
        return false;
    }
    /*
     * 跳过边界检查且不返回已删除值的私有删除方法
     * fastRemove(int index)相对于remove(int index)少了检查索引越界的操作,可见jdk将性能优化到极致
     * Private remove method that skips bounds checking and does not return the value removed.
     */
    private void fastRemove(int index) {
    	//修改次数加1
        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
    }

执行流程:

  1. 找到第一个等于指定元素值的元素;
  2. 快速删除;

到此结束,感谢阅读(*^▽^*)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2420.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++笔试强训】第十八天

&#x1f387;C笔试强训 博客主页&#xff1a;一起去看日落吗分享博主的C刷题日常&#xff0c;大家一起学习博主的能力有限&#xff0c;出现错误希望大家不吝赐教分享给大家一句我很喜欢的话&#xff1a;夜色难免微凉&#xff0c;前方必有曙光 &#x1f31e;。 &#x1f4a6;&a…

Dubbo源码学习(八)ScopeBeanFactory对比Spring 的BeanFactory

目录 1. ScopeBeanFactory与BeanFactory对比 2. 注册Bean 3. 执行一系列的PostProccessor 1. ScopeBeanFactory与BeanFactory对比 ScopeBeanFactory是Dubbo自己定义的管理Bean的一个类, 类似于Spring BeanFactory注册管理Bean的方式&#xff0c; 不同的是Spring BeanFactor…

软考下午第5题——面向对象程序设计——代码填空(老程序员必得15分)

第五个题目分为C 和 Java两个题目&#xff0c;除去编写代码不同&#xff0c;考察的内容是完全相同的&#xff0c;选一个就行。建议Java&#xff0c;因为老程序员最近用的Java肯定对。 题目考察形式为给出类图描述和几乎全部代码&#xff0c;考生关键代码填空即可。 某软件公司…

【数据结构】简单认识:堆

数据结构&#xff1a;堆堆1.堆是什么&#xff1f;2.堆的特性。3.堆的操作原理①堆的插入原理②堆的删除原理堆 1.堆是什么&#xff1f; 堆是特殊的队列&#xff0c;不同于普通队列&#xff0c;从堆中取出元素是依照元素的优先级大小&#xff0c;而不是元素进入队列的先后顺序…

计算机毕业设计(附源码)python疫情防控管理系统

项目运行 环境配置&#xff1a; Pychram社区版 python3.7.7 Mysql5.7 HBuilderXlist pipNavicat11Djangonodejs。 项目技术&#xff1a; django python Vue 等等组成&#xff0c;B/S模式 pychram管理等等。 环境需要 1.运行环境&#xff1a;最好是python3.7.7&#xff0c;…

阿里/华为云服务器centos7.5 java部署环境快速搭建一条龙【git、maven、jdk8、docker安装nginx、mysql、redis】

文章目录linux常用命令汇总视频教程云服务器搭建java部署环境1.安装配置git2.安装jdk和maven下载安装3.安装docker4.安装docker-compose5.编排nginx6.编排mysql7.编排redislinux常用命令汇总 linux常用命令汇总 视频教程 云服务器java环境搭建一条龙&#xff08;1&#xff0…

数据分析 | Pandas 200道练习题,每日10道题,学完必成大神(6)

文章目录前期准备1. 使用绝对路径读取本地Excel数据2. 查看数据前三行3. 查看每一列数据缺失值情况4. 提取日期列含有空值的行5. 输出每列缺失值具体行的情况6. 删除所有缺失值的行7. 绘制收盘价的折线图8. 同时绘制开盘价与收盘价9. 绘制涨跌的直方图10. 让直方图给更细致本章…

MPEG vs JPEG

MPEG 是什么呢&#xff1f;看着很熟悉&#xff0c;于是想起了 FFmpeg。 于是不禁要问&#xff1a;二者有关系吗&#xff1f; FFmpeg 是一个完整的跨平台音视频解决方案&#xff0c;它可以用于处理音频和视频的转码、录制、流化处理等操作。其实是 FFmpeg 取名借鉴了 MPEG&…

UE4 回合游戏项目 02- 创建人物-敌人角色(动画蓝图练习)

在上一节&#xff08;UE4 回合游戏项目 01- 创建人物-玩家角色&#xff09;基础上创建敌人角色的动画蓝图 步骤&#xff1a; 1.创建动画蓝图 选择怪物骨骼 命名为enemy1_AnimBP 2.双击打开enemy1_AnimBP&#xff0c;创建一个新的状态机节点&#xff0c;连接到输出姿势 3.双击…

计算机毕业设计(51)java小程序毕设作品之教室图书馆座位预约小程序系统

项目背景和意义 目的&#xff1a;本课题主要目标是设计并能够实现一个基于微信小程序预约订座小程序&#xff0c;前台用户使用小程序&#xff0c;后台管理使用JavaMysql开发&#xff0c;后台使用了springboot框架&#xff1b;通过后台添加座位类型、座位号&#xff0c;用户通过…

JVM 的发展历程及其基本概念 (一)

一、JVM的基本介绍 1、随着Java7的正式发布&#xff0c;Java 虛拟机的设计者们通过JSR-292规范基本实现在Java虚拟机平台上运行非Java语言编写的程序。 Java虚拟机根本不关心运行在其内部的程序到底是使用何种编程语言编写的&#xff0c;它只关心“字节码”文件。也就是说Ja…

java线程简介

文章目录前言Java线程简介多线程的优点线程的优先级线程的状态daemon线程总结前言 很多地方我们都会用到线程&#xff0c;java操作系统的线程本质其实就是&#xff0c;你写了一个线程类&#xff0c;java替你一对一的在操作系统层面创建了一个线程。之前应该是这样的&#xff0…

【HTML】标签下合集~~~

&#x1f60a;博主页面&#xff1a;鱿年年 &#x1f449;博主推荐专栏&#xff1a;《WEB前端》&#x1f448; ​&#x1f493;博主格言&#xff1a;追风赶月莫停留&#xff0c;平芜尽处是春山❤️ 目录 一、图像标签和路径&#xff08;重点&#xff09; 1.图像标签 2.路径…

直播间数字化新趋势:打造内容良性循环

一年一度的「双十一」又来了&#xff0c;还记得去年的「双十一」热点吗&#xff1f; 去年「双十一」&#xff0c;李佳琦当天直播超过 12 小时&#xff0c;观看人数达到 2.49 亿人&#xff0c;再加上另一个顶流薇娅&#xff0c;二人当天总销售额高达 189 亿元。 这个数字&#x…

排序算法-冒泡排序(工具类)

冒泡排序 什么是冒泡排序 冒泡排序&#xff08;Bubble Sort&#xff09;&#xff0c;是计算机科学领域简单的排序算法 重复的访问每一个元素&#xff0c;依次相邻的两个元素进行比较大小&#xff0c;进行交换位置&#xff0c; 为什么叫冒泡排序&#xff1a; 越小的元素会经…

C - Bricks and Bags,E - Hanging Hearts,H-Leonard的子序列_树状数组优化dp,B - Hash 河南省赛

14天阅读挑战赛 C - Bricks and Bags 情况考虑少了&#xff0c;以为把最大值和最小值单独放在两个包里是最优的&#xff0c;其实不是&#xff0c;应该是分别枚举i&#xff0c;分别和最大值或最小值单独放在两个包里&#xff0c;然后去更新答案 #include<bits/stdc.h> …

基于stm32 ESP8266WiFi模块的基本通信

文章目录前言一、什么是ESP8266&#xff1f;二、ESP8266常用指令集三、模块的配置 及 指令的使用四、程序设计前言 本篇涉及到的模块与工具为&#xff1a; 1. ATK-ESP8266wifi模块 2. USB-UART模块 3. 串口调试助手 提取链接&#xff1a;https://pan.baidu.com/s/17xRlpnjp8j-…

软考下午题第2题——E-R图 UML图 逻辑结构设计-示题与解析

下午的第二题主要是找【属性】【主键】【外键】【候选键】之间的关系。 候选键&#xff1a;属性或者是属性组合&#xff0c;其值能够唯一地标识一个元组 主键&#xff1a;在一个关系中可能有多个候选键&#xff0c;从中选择一个作为主键 外键&#xff1a;如果一个关系中的属性或…

【JavaWeb】会话跟踪技术Cookie与Session原始真解

文章目录1 什么是会话&#xff1f;2 Cookie技术2.1 Cookie简介2.2 Cookie的理解与创建2.3 服务器获取Cookie与Cookie的修改2.4 Cookie的生命控制与生命周期2.5 Cookie有效路径Path设置3 Session会话技术3.1 初探Session3.2 Session的创建、获取与基本使用3.3 Session的生命控制…

使用Python的smtplib模块发送带附件的邮件

上一篇文章《使用Python的smtplib模块发送简单邮件》介绍了调用smtplib模块发送包含简单内容的邮件&#xff0c;本文继续学习参考文献1中的发送带附件的邮件的示例代码&#xff0c;同时由于参考文献1中的带附件邮件中并没有邮件附件&#xff0c;而仅仅是邮件内容中关联的内嵌资…