首页 > 编程语言 >ArrayList源码解读

ArrayList源码解读

时间:2023-03-06 09:34:10浏览次数:48  
标签:capacity int ArrayList elementData private 解读 minCapacity 源码

1.创建ArrayList

List<String> list = new ArrayList<>();
list.add("wang");

2.构造方法:

elementData的长度就是ArrayList的容量,在第一次使用时,elementData的长度会扩展到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 = {};

/**
 * 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

/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }

3.add方法/**     * Appends the specified element to the end of this 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) {
      扩容 ensureCapacityInternal(size + 1); // Increments modCount!!
      插入元素
elementData[size++] = e; return true; }
  扩容
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        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.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = 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);
    }

Arrays的copyOf()方法传回的数组是新的数组对象,改变传回数组中的元素值,不会影响原来的数组。

copyOf()的第二个自变量指定要建立的新数组长度,如果新数组的长度超过原数组的长度,则保留数组默认值,例如:

import java.util.Arrays;

public class ArrayDemo {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5}; 
        int[] arr2 = Arrays.copyOf(arr1, 5);
        int[] arr3 = Arrays.copyOf(arr1, 10);
        for(int i = 0; i < arr2.length; i++) 
            System.out.print(arr2[i] + " "); 
            System.out.println();
        for(int i = 0; i < arr3.length; i++) 
            System.out.print(arr3[i] + " ");
    }
} 

运行结果:

1 2 3 4 5 
1 2 3 4 5 0 0 0 0 0

标签:capacity,int,ArrayList,elementData,private,解读,minCapacity,源码
From: https://www.cnblogs.com/wanglongjiang/p/17182648.html

相关文章

  • nsq 源码剖析
    简要介绍主流MQ比较:目前主流的MQ有Kafka,RabbitMQ,NSQ,RocketMQ,ActiveMQ等,它们的对比如下:NSQ组件Topic:一个topic就是程序发布消息的一个逻辑键,......
  • OpenMP task construct 实现原理以及源码分析
    OpenMPtaskconstruct实现原理以及源码分析前言在本篇文章当中主要给大家介绍在OpenMP当中task的实现原理,以及他调用的相关的库函数的具体实现。在本篇文章当中最......
  • JavaSE——ArrayList集合练习
    packagecom.zhao.test2;publicclassPhone{privateStringlogo;privateIntegerprice;publicPhone(){}publicPhone(Stringlogo,I......
  • JavaSE——集合ArrayList
    集合和数组的优势对比:长度可变添加数据的时候不需要考虑索引,默认将数据添加到末尾1.1ArrayList类概述什么是集合提供一种存储空间可变的存储模型,存储的数据......
  • 【代理】【七】代理源码解析-Cglib代理-为什么Spring中的代理方法互相调用 AOP 会失效
    1 前言今天我们来看个问题,我看源码的时候产生的困惑,就是我们都知道SpringAOP我们方法中调用第二个方法,第二个方法不会走增强的逻辑,而原生的Cglib方法互相调用是会走......
  • MASA Framework源码解读-01 MASAFacotry工厂设计
    序言闲来无聊,前段时间发现一个.net开源框架:masaframework。经过一些小型项目使用,发现确实挺不错的。然后我又去阅读了整个masaframework源码,特此来记录整个源码阅读的......
  • 「死磕源码系列之ants协程池」高性能协程池ants源码剖析
    1、简介ants是什么ants是一个高性能的goroutine池,实现了对大规模goroutine的调度管理、goroutine复用,允许使用者在开发并发程序的时候限制goroutine数量,复用资源,达......
  • Django源码-startproject
    Django源码-startprojectDjango的所有命令都位于django/django/core/management/commands/目录下一命令目录django-adminstartprojectproject_name这个命令在源码里......
  • Django源码-测试和调试环境搭建
    Django源码-测试和调试环境搭建一创建虚拟环境mkvirtualenv-ppython3.8.10DjangoSource二安装Djangopipinstalldjango==4.0b1三下载源码方法一gitclon......
  • TCP通信聊天服务端和客户端(C/C++语言开发)附完整源码
    距离上次学Python写的Python实现简单聊天室已经过去好久了,现在学c++又写了一遍,其实过程差不多,无非是语法的变化,目前仅实现最简单的一对一的通信,然后改就是了,接下来应该是......