当前位置: 首页 > news >正文

ArrayList列表解析

ArrayList集合

ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增长。在添加大量元素前,应用程序可以使用ensureCapacity操作来增加 ArrayList 实例的容量。这可以减少递增式再分配的数量。

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

List : 表明它是一个列表,支持添加、删除、查找等操作,并且可以通过下标进行访问。
RandomAccess :这是一个标志接口,表明实现这个接口的 List 集合是支持 快速随机访问 的。在 ArrayList 中,我们即可以通过元素的序号快速获取元素对象,这就是快速随机访问。
Cloneable :表明它具有拷贝能力,可以进行深拷贝或浅拷贝操作。
Serializable : 表明它可以进行序列化操作,也就是可以将对象转换为字节流进行持久化存储或网络传输,非常方便。

ArrayList 和 Vector 的区别

ArrayList 是 List 的主要实现类,底层使用 Object[]存储,适用于频繁的查找工作,线程不安全 。Vector 是 List 的古老实现类,底层使用Object[] 存储,线程安全。
ArrayList 中可以存储任何类型的对象,包括 null 值。不过,不建议向ArrayList 中添加 null 值, null 值无意义,会让代码难以维护比如忘记做判空处理就会导致空指针异常。

核心代码模拟解读

  • System.arrayCopy()
/***   复制数组* @param src 源数组* @param srcPos 源数组中的起始位置* @param dest 目标数组* @param destPos 目标数组中的起始位置* @param length 要复制的数组元素的数量*/public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);
package com.netty.myb.list;import java.util.*;/*** @program: java-study* @description: ArrayList模拟* @author: mengyb* @create: 2025-07-15 14:30**/public class ArrayListDemo<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{/*** 默认的容量*/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 = {};/*** 存储元素的数组*/transient Object[] elementData; // non-private to simplify nested class access/*** 数组集合的大小Size*/private int size;public static void main(String[] args) {List<String> list = new ArrayList<>();}public ArrayListDemo(int initialCapacity) {// 指定初始化的容量  则创建该容量的数组if (initialCapacity > 0) {// 创建一个初始的数组 Object[] elementData = new Object[initialCapacity];this.elementData = new Object[initialCapacity];} else if (initialCapacity == 0) {// 初始化容量为0,则建立一个空的数组  Object[] elementData = {};this.elementData = EMPTY_ELEMENTDATA;} else {throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}public ArrayListDemo() {// Object[] elementData = {};this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}public ArrayListDemo(Collection<? extends E> c) {// 将一个集合转化为 数组 Object[] a = {1,1,1}Object[] a = c.toArray();// 数组的大小 不为0if ((size = a.length) != 0) {// 判断是否为ArrayListif (c.getClass() == ArrayList.class) {// Object[] elementData = a;elementData = a;} else {// Object[] elementObject = {1,2,3}; 长度为sizeelementData = Arrays.copyOf(a, size, Object[].class);}} else {// replace with empty array.// 如果数组为0 则创建一个空数组 Object[] elementData = {}elementData = EMPTY_ELEMENTDATA;}}@Overridepublic E get(int index) {return null;}@Overridepublic int size() {return size;}/*** 浅拷贝* @return*/public Object clone() {try {// 浅拷贝ArrayListDemo<?> v = (ArrayListDemo<?>) super.clone();// 实现数组的复制,返回复制后的数组v.elementData = Arrays.copyOf(elementData, size);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError(e);}}/*** Arrays.copyOf(目标数组, 大小); 将Object[]数组拷贝出来*/public Object[] toArray() {return Arrays.copyOf(elementData, size);}public <T> T[] toArray(T[] a) {if (a.length < size)// Make a new array of a's runtime type, but my contents:return (T[]) Arrays.copyOf(elementData, size, a.getClass());// System.arraycopy(目标数组,从第几个开始,复制进新数组, 从新数组的第几个开始, 复制的长度为size)// Object[] a = elementData;System.arraycopy(elementData, 0, a, 0, size);// 新数组的长度 大于 elementData的长度if (a.length > size)a[size] = null;return a;}/*** 获取数组 通过下标索引获取指定的元素* @param index index of the element to return* @return*/public E get(int index) {// 检查 index 是否越界rangeCheck(index);// 从Object[] elementData数组中获取指定的下标值return elementData(index);}/*** 检查索引index 是否 超出Object[] elementData的长度* @param index*/private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}/*** 根据下标索引从数组中获取元素* @param index* @return*/@SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}/*** 新增元素,在数组的最后添加元素* @param e* @return*/public boolean add(E e) {// 扩容 1ensureCapacityInternal(size + 1);  // Increments modCount!!// 将Object[] elementData 数组容量+1elementData[size++] = e;return true;}/***  在指定位置新增元素* @param index 增加元素的索引* @param element*/public void add(int index, E element) {// 1 范围检测 判断是否越界rangeCheckForAdd(index);// 2 扩容ensureCapacityInternal(size + 1);  // Increments modCount!!// 3、将原数组复制到新数组中, 将elementData扩容后, index后面的元素 放到扩容后的index+1后System.arraycopy(elementData, index, elementData, index + 1,size - index);// 4、将扩容后,空闲出来的index索引元素 赋值为elementelementData[index] = element;// 5、将统计容量的size+1size++;}// 判断下标是否越界private void rangeCheckForAdd(int index) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}/*** 删除指定元素* @param o  元素* @return*/public boolean remove(Object o) {if (o == null) {// 找到 null 的元素索引for (int index = 0; index < size; index++)if (elementData[index] == null) {fastRemove(index);return true;}} else {// 找到非null元素的索引for (int index = 0; index < size; index++)if (o.equals(elementData[index])) {// 找到删除元素的下标索引fastRemove(index);return true;}}return false;}/*** 根据下标索引删除元素* @param index 4*/private void fastRemove(int index) {modCount++;// 数组移动 8-4-1 = 5int numMoved = size - index - 1;if (numMoved > 0)// 将index后的元素复制到 index-1后的位置,最后一个元素需要被删除System.arraycopy(elementData, index+1, elementData, index,numMoved);// 删除最后一个元素elementData[--size] = null; // clear to let GC do its work}// 清空元素public void clear() {modCount++;// clear to let GC do its work// 将Object[] 的所有元素设置为nullfor (int i = 0; i < size; i++)elementData[i] = null;size = 0;}/*** 删除指定范围的元素* @param fromIndex index of first element to be removed* @param toIndex index after last element to be removed*/protected void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = size - toIndex;// 将范围以外的元素,赋值给formIndex开始的位置System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// clear to let GC do its work// 新的数组大小Object[]int newSize = size - (toIndex-fromIndex);for (int i = newSize; i < size; i++) {// 新的数组后的元素设置为nullelementData[i] = null;}size = newSize;}/*** 扩容第一步* @param minCapacity  在原来的size + 1*/private void ensureCapacityInternal(int minCapacity) {// 开始扩容ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}/*** 扩容 1.1* @param elementData 原数组* @param minCapacity 最小容量 size + 1* @return*/private static int calculateCapacity(Object[] elementData, int minCapacity) {// 判断当前数组Object[] elementData 是否是 {} 空的if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {// elementData = {};  在 默认容量10 与 现在的容量 进行比较 获取最大的那个值return Math.max(DEFAULT_CAPACITY, minCapacity);}// 返回现在的容量 size + 1return minCapacity;}/*** 扩容 1.2 步骤* @param minCapacity DEFAULT_CAPACITY > size + 1 ? 10 : size+1*/private void ensureExplicitCapacity(int minCapacity) {modCount++;// overflow-conscious code// 判断是否扩容成功if (minCapacity - elementData.length > 0)// 扩容第二布grow(minCapacity);}/*** TODO 数组的最大长度为 Integer.MAX_VALUE-8*/private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;/*** 扩容 2.1* @param minCapacity DEFAULT_CAPACITY > size + 1 ? 10 : size+1*/private void grow(int minCapacity) {// overflow-conscious code// 原容量大小int oldCapacity = elementData.length;// 新容量 =  原容量 + 原容量/2;int newCapacity = oldCapacity + (oldCapacity >> 1);// 新容量 > size + 1;if (newCapacity - minCapacity < 0)// newCapacity = DEFAULT_CAPACITY > size + 1 ? 10 : size+1newCapacity = minCapacity;if (newCapacity - MAX_ARRAY_SIZE > 0) // 判断新容量是否超过最大限制// 超过最大限制了,处理方案newCapacity = hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:// 没有超过最大限制 将新容量赋值给原数组,完成扩容elementData = Arrays.copyOf(elementData, newCapacity);}/*** 扩容 2.2 newCapacity新容量 超出了 最大值Integer.MAX_VALUE-8 的限制 后处理方案* @param minCapacity  DEFAULT_CAPACITY > size + 1 ? 10 : size+1* @return*/private static int hugeCapacity(int minCapacity) {//if (minCapacity < 0) // overflow// 内存溢出throw new OutOfMemoryError();// DEFAULT_CAPACITY > size + 1 ? 10 : size+1  > Integer.MAX_VALUE-8 : Integer.MAX_VALUE : Integer.MAX_VALUE-8// 返回一个新的容量 要不然是 Integer的最大值,要不然返回数组的最大限制return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}}

文章转载自:
http://apperceive.pzdurr.cn
http://brazzaville.pzdurr.cn
http://amplify.pzdurr.cn
http://axiological.pzdurr.cn
http://choker.pzdurr.cn
http://buddhahood.pzdurr.cn
http://choosing.pzdurr.cn
http://addax.pzdurr.cn
http://astounding.pzdurr.cn
http://changsha.pzdurr.cn
http://aftereffect.pzdurr.cn
http://anharmonic.pzdurr.cn
http://amidships.pzdurr.cn
http://cartesianism.pzdurr.cn
http://careless.pzdurr.cn
http://aquarelle.pzdurr.cn
http://anabiosis.pzdurr.cn
http://arboriculture.pzdurr.cn
http://cheltonian.pzdurr.cn
http://charmed.pzdurr.cn
http://chromogenic.pzdurr.cn
http://cage.pzdurr.cn
http://challah.pzdurr.cn
http://blackwash.pzdurr.cn
http://bedecked.pzdurr.cn
http://boeotia.pzdurr.cn
http://arsenotherapy.pzdurr.cn
http://chrematistic.pzdurr.cn
http://batfish.pzdurr.cn
http://babyish.pzdurr.cn
http://www.dtcms.com/a/281559.html

相关文章:

  • GCC属性修饰符__attribute__((unused))用途
  • 2025国自然青基、面上资助率,或创新低!
  • IPSec和HTTPS对比(一)
  • Java使用itextpdf7生成pdf文档
  • GAMES101 lec1-计算机图形学概述
  • 前端-CSS-day4
  • 边缘计算中模型精度与推理速度的平衡策略及硬件选型
  • 实战长尾关键词SEO优化指南提升排名
  • Go语言调度器深度解析:sysmon的核心作用与实现原理
  • Web3.0 学习方案
  • ROS第十五梯:launch进阶用法——conda自启动和多终端多节点运行
  • Axios 和Express 区别对比
  • 前端打包自动压缩为zip--archiver
  • Bp神经网络公式导出方法
  • 【SpringBoot】实战-开发模式及环境搭建
  • 学习嵌入式的第二十八天-数据结构-(2025.7.15)进程和线程
  • For and While Loop
  • javaScript 基础知识(解决80%js面试问题)
  • 代码随想录算法训练营十六天|二叉树part06
  • 配置nodejs,若依
  • 【08】MFC入门到精通——MFC模态对话框 和 非模态对话框 解析 及 实例演示
  • Git未检测到文件更改
  • 密码协议的基本概念
  • bytetrack漏检补齐
  • Nginx配置反向代理
  • 【世纪龙科技】智能网联汽车环境感知系统教学软件
  • C# StringBuilder源码分析
  • Java大厂面试实录:从Spring Boot到AI微服务架构的层层递进
  • 华为OD 特异双端队列
  • 魔搭官方教程【快速开始】-swift 微调报错:`if v not in ALL_PARALLEL_STYLES`