【Java系列】ArrayList源码解析 您所在的位置:网站首页 arraylist源码 【Java系列】ArrayList源码解析

【Java系列】ArrayList源码解析

2024-03-06 16:17| 来源: 网络整理| 查看: 265

温馨提示:本文源码分析基于JDK 1.8。

目录

ArrayList简介

ArrayList 核心源码分析

底层数据结构

构造函数

自动扩容

add 方法

grow方法

ArrayList简介

ArrayList 实现了 List 接口,是有序集合,即用户可以精确控制每个元素在列表中的插入位置,允许放入 null 元素,底层通过数组实现,支持动态扩容。每个 ArrayList 都有一个容量(capacity),表示底层数组的实际大小。当向容器中添加元素时,如果容量不足,容器会自动增大底层数组的大小。

先来看一张 ArrayList 的类图:

ArrayList 继承 AbstractList,实现了 List,RandomAccess,Cloneable,java.io.Serializable这些接口。

List:提供添加、删除、查找等操作,并且可以通过下标进行访问。RandomAccess:提供 快速随机访问 能力。Cloneable:表明它具有拷贝能力,可以进行深拷贝或浅拷贝操作。Serializable:表明它可以被序列化操作,也就是将对象转化为字节流进行网络传输,非常方便。 ArrayList 核心源码分析 底层数据结构

这里的数组是一个Object数组,以便能够容纳任何类型的对象。

/** * 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 时,会初始化赋值为一个空数组。当真正对 ArrayList 添加元素时,才会真正分配容量,数组容量默认扩充为 10。在下面自动扩容章节会详细介绍。

/** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; /** * 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 = {}; /** * 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); } } /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public ArrayList(Collection


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有