今天上午上课在看JavaSE的面经,其中有问关于ArrayList和LinkedList的区别,就突然思考到,既然ArrayList是采用数组形式存储数据,对比我们自己使用到的数组,为什么ArrayList的容量似乎是“无限”的。关于这个问题,我查看了ArrayList的源码。

@java.io.Serial
private static final long serialVersionUID = 8683452581122892189L; /**
* Default initial capacity.
*/
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 Object[] elementData; // non-private to simplify nested class access /**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;

其中真正存放数据的是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);
}
} /**
* 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<? extends E> c) {
Object[] a = c.toArray();
if ((size = a.length) != 0) {
if (c.getClass() == ArrayList.class) {
elementData = a;
} else {
elementData = Arrays.copyOf(a, size, Object[].class);
}
} else {
// replace with empty array.
elementData = EMPTY_ELEMENTDATA;
}
}

ArrayList中含有三个构造函数,根据是否指定初始容量、有无原数据等执行不同函数。

public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}

这段代码是将ArrayList中的实际容量(size)与数组长度(elementData.length)对比,如果数组长度有多余,就对原数据进行复制然后修改成新的长度

public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
} /**
* Copies the specified array, truncating or padding with nulls (if necessary)
* so the copy has the specified length. For all indices that are
* valid in both the original array and the copy, the two arrays will
* contain identical values. For any indices that are valid in the
* copy but not the original, the copy will contain {@code null}.
* Such indices will exist if and only if the specified length
* is greater than that of the original array.
* The resulting array is of the class {@code newType}.
*
* @param <U> the class of the objects in the original array
* @param <T> the class of the objects in the returned array
* @param original the array to be copied
* @param newLength the length of the copy to be returned
* @param newType the class of the copy to be returned
* @return a copy of the original array, truncated or padded with nulls
* to obtain the specified length
* @throws NegativeArraySizeException if {@code newLength} is negative
* @throws NullPointerException if {@code original} is null
* @throws ArrayStoreException if an element copied from
* {@code original} is not of a runtime type that can be stored in
* an array of class {@code newType}
* @since 1.6
*/
@IntrinsicCandidate
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}

这段就是把旧数据复制到新数组上的代码片段。

    /**
* Increases the capacity of this {@code ArrayList} 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) {
if (minCapacity > elementData.length
&& !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
&& minCapacity <= DEFAULT_CAPACITY)) {
modCount++;
grow(minCapacity);
}
} /**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
* @throws OutOfMemoryError if minCapacity is less than zero
*/
private Object[] grow(int minCapacity) {
int oldCapacity = elementData.length;
if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
int newCapacity = ArraysSupport.newLength(oldCapacity,
minCapacity - oldCapacity, /* minimum growth */
oldCapacity >> 1 /* preferred growth */);
return elementData = Arrays.copyOf(elementData, newCapacity);
} else {
return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
}
} private Object[] grow() {
return grow(size + 1);
}

ArrayList中也还有验证容量的函数(ensureCapacity),通过grow函数增长数组长度。一般情况下newCapacity = oldCapacity + oldCapacity >> 1,所以ArrayList每次扩容大概是旧容量的1.5倍。如果需要扩容的大小过大(和int类型最大值比较),就直接返回一个最大int类型数大小的数组。

ArrayList扩容问题的更多相关文章

  1. 都说新的Arraylist 扩容是(1.5倍+1) 看了1.8的源代码发现不是这么回事

    都说新的Arraylist 扩容是(1.5倍+1) 看了1.8的源代码发现不是这么回事 就用下面这段代码在jdk的三个版本运行看了下效果 import java.lang.reflect.Field; ...

  2. 分享知识-快乐自己:都说新的Arraylist 扩容是(1.5倍+1) 看了1.8的源代码发现不是这么回事

    都说新的Arraylist 扩容是(1.5倍+1) 看了1.8的源代码发现不是这么回事 就用下面这段代码在jdk的三个版本运行看了下效果: import java.lang.reflect.Field ...

  3. ArrayList 扩容原理

    面试中经常问到的问题之一就是List的扩容机制了,他是怎么做到扩容的,大家都能答出来底层是数组,复制一个数组来扩容,但是再具体一点来说,大家就不知道该怎么说了,如果不看源码说这么多确实就差不多了,但是 ...

  4. coding++:都说新的Arraylist 扩容是(1.5倍+1) 看了1.8的源代码发现不是这么回事

     都说新的Arraylist 扩容是(1.5倍+1) 看了1.8的源代码发现不是这么回事 就用下面这段代码在jdk的三个版本运行看了下效果: import java.lang.reflect.Fiel ...

  5. ArrayList扩容机制实探

    ArrayList初始化 问题:执行以下代码后,这个list的列表大小(size)和容量(capacity)分别是多大? List<String> list = new ArrayList ...

  6. ArrayList扩容机制

    一.先从 ArrayList 的构造函数说起 ArrayList有三种方式来初始化,构造方法源码如下: 1 /** 2 * 默认初始容量大小 3 */ 4 private static final i ...

  7. ArrayList扩容

    jdk1.5 public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new Illega ...

  8. ArrayList扩容分析

    一段java代码 String e = "q3234v"; List<String> list = new ArrayList<String>(); for ...

  9. ArrayList扩容原理分析

    1:代码解读和分析 1.1:构造方法分析 1: public ArrayList(int initialCapacity) { ) { this.elementData = new Object[in ...

  10. ArrayList 扩容 和 Vector

    public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[siz ...

随机推荐

  1. AE功能扩展一

    1.添加栅格影像 基本思路:声明栅格工作空间→创建栅格数据集对象→创建金字塔→声明图层对象→刷新地图控件 private void AddBaseMap(string filepath) { IWor ...

  2. vue2版本中slot的基本使用详解

    前言 在vue的开发过程中,我们会经常使用到vue的slot插槽组件,vue官方文档的描述: Vue 实现了一套内容分发的 API,这套 API 的设计灵感源自 Web Components 规范草案 ...

  3. 【机器学习基础】无监督学习(2)——降维之LLE和TSNE

    在上一节介绍了一种最常见的降维方法PCA,本节介绍另一种降维方法LLE,本来打算对于其他降维算法一并进行一个简介,不过既然看到这里了,就对这些算法做一个相对详细的学习吧. 0.流形学习简介 在前面PC ...

  4. 040_Eureka 服务注册与发现

    目录 什么是Eureka 原理讲解 Eureka的基本架构 三大角色 盘点目前工程状况 创建Eureka服务端子模块 springcloud-eureka-7001 导入依赖 pom.xml 配置文件 ...

  5. springsecurity-01-0511

    springsecurity-01-0511课堂代码 BaseController package com.springsecurity.springsecurity.controller; impo ...

  6. CentOS7部署Bind

    镜像下载.域名解析.时间同步请点击 阿里巴巴开源镜像站 1.简介 DNS(Domain Name System),域名系统,因特网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问 ...

  7. ZYNQ生成一个工程的基本步骤

    Zynq 7000 SoC 是业界首款All Programmable SoC 组成: PL(FPGA部分) PS(ARM部分) PL和PS数据传输的 高效接口:AXI和ACP PS: 处理系统(Pr ...

  8. CF932G Palindrome Partition(回文自动机)

    CF932G Palindrome Partition(回文自动机) Luogu 题解时间 首先将字符串 $ s[1...n] $ 变成 $ s[1]s[n]s[2]s[n-1]... $ 就变成了求 ...

  9. 深度优先算法--对DFS的一些小小的总结(一)

    提到DFS,我们首先想到的是对树的DFS,例如下面的例子:求二叉树的深度 int TreeDepth(BinaryTreeNode* root){ if(root==nullptr)return 0; ...

  10. 一、mycat介绍

    一.背景 随着时间和业务的发展,数据库中的数据量增长是不可控的,库和表中的数据会越来越大,随之带来的是更高的磁盘.IO.系统开销,甚至性能上的瓶颈,而一台服务的资源终究是有限的,因此需要对数据库和表进 ...