java集合之ArrayList分析
概述
ArrayList是List集合的列表经典实现,其底层采用定长数组实现,可以根据集合大小进行自动扩容。
代码基于jdk1.8
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
特点
- 快速随机访问
- 允许存放多个null元素
- 底层是Object数组
- 增加元素个数可能很慢(可能需要扩容),删除元素可能很慢(可能需要移动很多元素),改对应索引元素比较快
ArrayList底层实现原理
底层数据结构
数组
类成员变量
//默认初始化大小 private static final int DEFAULT_CAPACITY = 10; //空列表数据,初始化如果没有指定大小,则将此值赋予elementData private static final Object[] EMPTY_ELEMENTDATA = {}; //默认空列表数据,如果没有指定大小,那么将此值赋予elementData private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //列表数据 transient Object[] elementData;//transient标识是不被序列化 //列表大小 private int size;
注意到,底层容器数组的前面有一个transient关键字,啥意思??
查阅资料后,大概知道:transient标识之后是不被序列化的
但是ArrayList实际容器就是这个数组为什么标记为不序列化??那岂不是反序列化时会丢失原来的数据?
其实是ArrayList在序列化的时候会调用writeObject(),直接将size和element写入ObjectOutputStream;反序列化时调用readObject(),从ObjectInputStream获取size和element,再恢复到elementData。
原因在于elementData是一个缓存数组,它通常会预留一些容量,等容量不足时再扩充容量,那么有些空间可能就没有实际存储元素,采用上诉的方式来实现序列化时,就可以保证只序列化实际存储的那些元素,而不是整个数组,从而节省空间和时间。
常见方法
构造方法
从第一个构造方法可以看到,如果没有指定大小,那么就将elementData赋值为DEFAULTCAPACITY_EMPTY_ELEMENTDATA。
而从第二个构造方法可以看到,如果指定了大小为0,那么就将elementData赋值为EMPTY_ELEMENTDATA。
//空构造方法 public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } //指定大小 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); } } //指定初始集合 public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
插入add()方法
插入一共有两种实现方式,第一种是直接插入列表尾部,另一种是插入某个位置
/** * 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). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ //直接插入尾部 public boolean add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * 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). * * @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); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
- 如果是直接插入尾部的话,那么只需调用ensureCapacityInternal方法做容量检测。如果空间足够,那么就插入,空间不够就扩容后插入。
- 如果是插入的是某个位置,那么就需要将index之后的所有元素后移一位,之后再将元素插入至index处
查找get()方法
获取的源码非常简单,只需对index做有效性校验。
如果参数合法,那么直接返回对应数组下标的数据
public E get(int index) { rangeCheck(index); return elementData(index); } E elementData(int index) { return (E) elementData[index]; }
删除remove()方法
ArrayList的删除方法有两个,分别是:
- 删除某个位置的元素:remove(int index)
- 删除某个具体的元素:remove(Object o)
我们先来看第一个删除方法:删除某个位置的元素
/** * 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; // Let gc do its work return oldValue; }
上述代码的逻辑大致是这样的:首先做参数范围检测,接着将index位置后的所有元素都往前挪一位,最后减少列表大小。
第二个删除方法:删除某个特定的元素。
/** * 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 ? get(i)==null : 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; }
上述代码的逻辑大致是:首先,遍历列表的所有元素,找到需要删除的元素索引,左后调用fastRemove方法删除该元素。我们继续看看fastRemove方法的实现。
/* * Private remove method that skips bounds checking and does not * return the value removed. */ //用私有的方法 fastRemove 方法跳过边界,不返回删除值。 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 }
这里有一个疑问,那就是为什么不直接复用remove(int index)方法,而要新写一个方法。答案在 fastRemove 方法的注释中已经写了,就是为了跳过边界检查,提高效率。
扩容操作
扩容是ArrayList的核心方法,当插入的时候容量不足,便会触发扩容。我们可以看到在插入的两个方法中都调用了扩容方法——ensureCapacity。
/** * Increases the capacity of this <tt>ArrayList</tt> instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1;//扩容为原来的1.5倍+1 if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } }
Arrays.copyOf()去浅拷贝。
java中一个对象包含一个指向字符串的字段,浅拷贝的意思就是拷贝这个对象,那么他们的这个字段指向字符串是同一个。
浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象还是共享同一块内存。但深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象。
总结
经过上面的分析,我们可以知道ArrayList有如下特点:
- 底层基于数组实现,读取速度快,修改慢(读取时间复杂度O(1)),修改复杂度O(n)。
- 非线程安全
- ArrayList每次默认扩容为原来的1.5倍。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术