Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >ArrayList 源码分析

ArrayList 源码分析

作者头像
Jacob丶
发布于 2020-08-05 10:07:47
发布于 2020-08-05 10:07:47
41700
代码可运行
举报
文章被收录于专栏:JacobJacob
运行总次数:0
代码可运行

介绍

ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量能动态增长。

结构

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  • ArrayList 继承了AbstractList,实现了List。AbstractList、List提供了相关的添加、删除、修改、遍历等功能。
  • ArrayList 实现了RandmoAccess接口,即提供了随机访问功能。在ArrayList中,我们即可以通过元素的序号快速获取元素对象,这就是快速随机访问。
  • ArrayList 实现了Cloneable接口,实现clone(),实现克隆。
  • ArrayList 实现java.io.Serializable接口,意味着ArrayList支持序列化,能通过序列化去传输。

扩展:ArrayList和Vector不同,ArrayList中的操作不是线程安全的!所以,建议在单线程中才使用ArrayList,而在多线程中可以选择Vector。

字段

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    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.
     * 空数组实例
     * - 当用户没有指定 ArrayList 的容量时(即调用无参构造函数),返回的是该数组==>刚创建一个 ArrayList 时,其内数据量为 0。
     * - 当用户第一次添加元素时,该数组将会扩容,变成默认容量为 10(DEFAULT_CAPACITY) 的一个数组===>通过  ensureCapacityInternal() 实现
     */
    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 关键字最主要的作用就是当序列化时,被transient修饰的内容将不会被序列化
     */
    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;

    /**
    * 这个列表在结构上被修改的次数。结构修改是指改变列表的大小,或者以一种正在进行的迭代可能会保留不正确结果的方式扰乱列表。
    */
    protected transient int modCount = 0;

提示:size和elementData.length是不相同的。size是指当前集合中存在的元素个数,elementData.length是指当前集合指定的容量大小例如,如果我们ArrayList()时,ArrayList只是给我们默认的elementData=DEFAULTCAPACITY_EMPTY_ELEMENTDATA,此时只是空数组,只有第一次add时才默认数组的大小为DEFAULT_CAPACITY=10 ,此时elementData.length=10,而size=0

构造方法

ArrayList提供了三种构造方法:
ArrayList(int initialCapacity)

构造一个指定容量的ArrayList。这是一个带初始容量大小的有参构造函数。

  • 初始容量>0:返回指定容量的大小
  • 初始容量=0:返回空数组
  • 初始容量<0:抛出异常 IllegalArgumentException
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Constructs an empty list with the specified initial capacity.
     * - 构造一个指定容量的ArrayList。这是一个带初始容量大小的有参构造函数。
     * @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);
        }
    }
ArrayList()

无参构造方法,创建ArrayList对象的时候不传入参数,则使用此无参构造方法创建ArrayList对象。从前面知道DEFAULTCAPACITY_EMPTY_ELEMENTDATA是一个空的Object[],给到elementData进行初始化,elementData也是个Object[]类型。当有元素进行第一次添加 add() 时,elementData将会变成默认的长度10。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Constructs an empty list with an initial capacity of ten.
     * - 无参构造方法,创建ArrayList对象的时候不传入参数,则使用此无参构造方法创建ArrayList对象
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

注意:默认容量为10,调用无参构造此时的容量0,当第一次调用 add() 方法时才进行扩容为10。

ArrayList(Collection<? extends E> c)

构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。

  • 将 Collection 对象转换成数组并赋值给 elementData。
  • 判断数组大小是否等于0,将空数组 EMPTY_ELEMENTDATA 赋值给 elementData。
  • 如果size的值大于0,则执行Arrays.copy方法,把collection对象的内容(可以理解为深拷贝)拷贝到elementData中。
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     * - 构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。
     * @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) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                // copyOf(要复制的数组,要返回的副本的长度,要返回的副本的类)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            // 将空数组 EMPTY_ELEMENTDATA 赋值给 elementData。
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

总结:ArrayList 构造方法就是初始化存储数据容器。存储数据容器其本质就是数组,在ArrayList中叫elementData。

普通方法

add()
add(E e)

将指定的元素添加此集合的末尾。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * 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) {
        // 检查数组容量,不够,容器+1,
        // 注意:只+1,因为add()一次只添加一个元素,并且也能确保资源不被浪费。
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //添加对象,自增size 等同于 elementData[size]; size++;
        elementData[size++] = e;
        return true;
    }
    // 检查数组容量,不够扩容。
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            //若 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 则取 DEFAULT_CAPACITY 和 minCapacity 的最大值
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return 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;
        // >>:表示右移,如果该数为正,则高位补0,若为负数,则高位补1
        // eg : 10 的二进制(1010) 右移 变成 0101(十进制5),所以扩容是1.5倍
        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:
        // 拷贝数组,改变容量大小。
        // Arrays.copyof(原数组,新的数组长度)
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    // 进行大容量分配
    private static int hugeCapacity(int minCapacity) {
        // 如果minCapacity<0,抛出异常
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        // 如果想要的容量大于MAX_ARRAY_SIZE,则分配Integer.MAX_VALUE,否则分配MAX_ARRAY_SIZE
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
  1. 第一次调用add方法流程分析
    1. 调用 add() ,此时 size=0 ,size+1=1;
    2. 调用 ensureCapacityInternal(minCapacity) ,此时 minCapacity=1;
    3. 调用 calculateCapacity(elementData,minCapacity) ,此时 minCapacity=1 ,elementData={}, DEFAULT_CAPACITY=10 ,DEFAULTCAPACITY_EMPTY_ELEMENTDATA={};
    4. 因为 elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA 所以取 DEFAULT_CAPACITY ,minCapacity两数最大值 DEFAULT_CAPACITY;
    5. 返回 ensureCapacityInternal后,调用 ensureExplicitCapacity(minCapacity) ,此时 minCapacity=10, elementData.length=0;
    6. 因为 minCapacity - elementData.length > 0调用 grow();
    7. 先扩容 newCapacity = newCapacity + ( newCapacity >> 1 ),判断 newCapacity - minCapacity < 0,所以 newCapacity = minCapacity = 10;
    8. 拷贝数组,改变容量大小;
    9. 一并返回到 add(),添加对象,自增size;
  2. 第二次扩容:第二次扩容是指当前集合中已经存在10(默认容量10)个元素后,继续添加第11个元素。
    1. 调用 add() ,此时 size=10 ,size+1=11;
    2. 调用 ensureCapacityInternal(minCapacity) ,此时 minCapacity=11;
    3. 调用 calculateCapacity(elementData,minCapacity) ,此时 minCapacity=11 ,elementData.length=10, DEFAULT_CAPACITY=10 ,DEFAULTCAPACITY_EMPTY_ELEMENTDATA.length=0;
    4. 因为 elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA ,所以取 minCapacity=11;
    5. 返回 ensureCapacityInternal 后,调用 ensureExplicitCapacity(minCapacity) ,此时 minCapacity=11 ,elementData.length=10;
    6. 因为 minCapacity - elementData.length > 0 调用 grow();
    7. 先扩容 newCapacity = newCapacity + ( newCapacity >> 1 ) ,判断 newCapacity - minCapacity > 0,所以 newCapacity = newCapacity = 15;
    8. 拷贝数组,改变容量大小;
    9. 一并返回到add(),添加对象,自增size;
add(int index, E element)

指定元素插入到列表中的指定位置。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * 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);
        // 检查数组容量,不够,扩容
        // 注意:只+1,因为add()一次只添加一个元素,并且也能确保资源不被浪费。
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        // System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,要拷贝的长度)
        // 主要思想:将当前位于该位置的元素(如果有)和任何后续元素向右移动(将一个元素添加到它们的索引中)。
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        // 指定索引位置赋值   
        elementData[index] = element;
        // 大小+1
        size++;
    }
    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        //要插入的索引位置不能小于0,不能大于size
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

总结:add(int index, E element)先检查索引是否越界,再判断是否需要扩容,再将需要右移的元素右移,最后赋值,修改大小。

remove
remove(int index)

删除列表中指定位置的元素。将后续所有元素向左移动(从它们的索引中减去1)。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     * - 删除列表中指定位置的元素。将后续所有元素向左移动(从它们的索引中减去1)。
     * @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);

        // 主要思想:
        // - 1. 先计算出需要左移的元素长度
        // - 2. 将后续所有元素向左移动(从它们的索引中减去1)。
        int numMoved = size - index - 1;
        if (numMoved > 0)
            // System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,要拷贝的长度)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        // 左移后,将最后一个元素至空
        elementData[--size] = null; // clear to let GC do its work
        // 返回删除的元素值
        return oldValue;
    }

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     * - 检查给定的索引是否在范围内。如果不是,则抛出适当的运行时异常。该方法不*not*检查索引是否为负数:它总是在数组访问之前使用,如果索引为负数,则会抛出ArrayIndexOutOfBoundsException。
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     * - 构造一个角标越界提示信息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    //获取指定索引的值
    E elementData(int index) {
        return (E) elementData[index];
    }

总结:remove(int index)先检查索引是否越界,然后计算出要左移的元素长度,最后左移。将最后一个元素至空。

remove(Object o)

从该列表中删除指定元素的第一个匹配项(如果存在)。如果列表不包含该元素,它将保持不变。确切的说,删除索引最小的元素

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * 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
     * - 返回true or false
     */
    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;
    }

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     * - 私有移除方法,该方法跳过边界检查且不返回被移除的值。
     */
    private void fastRemove(int index) {
        modCount++;
        // 计算要左移元素的长度
        int numMoved = size - index - 1;
        if (numMoved > 0)
            // System.arraycopy(源数组,源数组起始索引,目标数组,目标数组起始索引,要拷贝的长度)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        // 左移后,将最后一个元素至空
        elementData[--size] = null; // clear to let GC do its work
    }

总结:remove(Object o):删除指定元素,不用检查索引越界。此方法只删除索引值最小的元素。

get(int index)

返回列表中指定位置的元素。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Returns the element at the specified position in this list.
     * - 返回列表中指定位置的元素。
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        // 检查索引是否越界
        rangeCheck(index);
        // 获取指定索引上的元素
        return elementData(index);
    }
set(int index, E element)

将列表中指定位置的元素替换为指定元素。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     * - 将列表中指定位置的元素替换为指定元素。
     * @param index index of the element to replace
     * - 要替换的元素的索引
     * @param element element to be stored at the specified position
     * - 元素存储在指定位置
     * @return the element previously at the specified position
     * - 先前位于指定位置的元素
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        // 检查索引越界
        rangeCheck(index);
        // 获取指定位置的元素
        E oldValue = elementData(index);
        // 替换指定位置的元素
        elementData[index] = element;
        // 返回被替换的元素
        return oldValue;
    }
indexOf(Object o)

返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最低的索引的元素

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * - 返回该列表中指定元素第一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最低的索引的元素
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
lastIndexOf(Object o)

返回指定元素最后一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最高的索引的元素

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index <tt>i</tt> such that
     * - 返回指定元素最后一次出现的索引,如果该列表不包含该元素,则返回-1。确切的说,返回最高的索引的元素
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }
clear()

从列表中删除所有元素。该调用返回后,列表将为空。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     * - 从列表中删除所有元素。该调用返回后,列表将为空。
     */
    public void clear() {
        modCount++;

        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-01-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
【数据结构】线性表 ( 线性表概念简介 | 顺序存储结构 / 链式存储结构 | 顺序存储结构 - 顺序表 List | 顺序表 ArrayList 源码分析 )
ArrayList 源代码地址 : https://www.androidos.net.cn/android/9.0.0_r8/xref/libcore/ojluni/src/main/java/java/util/ArrayList.java
韩曙亮
2023/10/11
2770
Java集合源码分析之ArrayList
分析一个类的时候,数据结构往往是它的灵魂所在,理解底层的数据结构其实就理解了该类的实现思路,具体的实现细节再具体分析。
须臾之余
2019/08/09
3630
ArrayList源码解析(1)
ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增长。在添加大量元素前,应用程序可以使用ensureCapacity操作来增加 ArrayList 实例的容量。这可以减少递增式再分配的数量。
黑洞代码
2021/01/28
3330
ArrayList源码学习
写文章要有一定的顺序,按照一定的模块进行学习是比较好的学习习惯。跳跃式的学习很容易导致心态的变化。这不仅是学习过程的事情更是生活上的事情。因此还是按部就班,今天学习一下ArrayList。
写一点笔记
2020/08/26
2060
ArrayList源码学习
Java集合:ArrayList详解
ArrayList是我们日常中最长用的集合之一,在使用列表时,除非特殊情况,我们一般都会选择使用ArrayList,本文就ArrayList的几个主要方法主要介绍,并结合几个图片来介绍几个重要操作。
Java架构师必看
2021/05/18
5340
Java集合:ArrayList详解
ArrayList源码分析
可以看到,在构造方法中直接将 elementData 指向 DEFAULTCAPACITY_EMPTY_ELEMENTDATA空数组,这个时候该ArrayList的size为初始值0。
周同学
2019/08/29
4790
ArrayList源码分析
Java ArrayList源码分析,带你拿下面试官(含扩容机制等重点问题分析)
这个项目是从20年末就立好的 flag,经过几年的学习,回过头再去看很多知识点又有新的理解。所以趁着找实习的准备,结合以前的学习储备,创建一个主要针对应届生和初学者的 Java 开源知识项目,专注 Java 后端面试题 + 解析 + 重点知识详解 + 精选文章的开源项目,希望它能伴随你我一直进步!
BWH_Steven
2021/02/24
1.7K1
Java ArrayList源码分析,带你拿下面试官(含扩容机制等重点问题分析)
【面试必备】透过源码角度一步一步带你分析 ArrayList 扩容机制
细心的同学一定会发现 :以无参数构造方法创建 ArrayList 时,实际上初始化赋值的是一个空数组。当真正对数组进行添加元素操作时,才真正分配容量。即向数组中添加第一个元素时,数组容量扩为10。 下面在我们分析 ArrayList 扩容时会降到这一点内容!
本人秃顶程序员
2019/05/17
6520
ArrayList
  ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增长。在添加大量元素前,应用程序可以使用ensureCapacity操作来增加 ArrayList 实例的容量。这可以减少递增式再分配的数量。
后端码匠
2019/09/30
1.2K0
ArrayList源码分析(基于jdk1.8)(一):源码及基本操作
ArrayList继承了AbstractList类,并实现了List, RandomAccess, Cloneable, java.io.Serializable等接口。其官方描述为 Resizable-array implementation of the List interface。阅读源码doc,如下:
冬天里的懒猫
2020/08/04
3800
ArrayList源码分析(基于jdk1.8)(一):源码及基本操作
ArrayList 源码分析
在 Java 中当创建数组时会在内存中划分一块连续的内存,然后当有数据进入的时候会将数据按顺序的存储在这块连续的内存中。当需要读取数组中的数据时,需要提供数组中的索引,然后数组根据索引将内存中的数据取出来,返回给读取程序。在 Java 中并不是所有的数据都能存储到数组中,只有相同类型的数据才可以一起存储到数组中。
希希里之海
2019/09/05
4720
jdk源码分析之ArrayList
* The array buffer into which the elements of the ArrayList are stored.
全栈程序员站长
2022/07/15
1600
死磕 Java集合之ArrayList源码分析
ArrayList是一种以数组实现的List,与数组相比,它具有动态扩展的能力,因此也可称之为动态数组。
彤哥
2019/07/08
4830
死磕 Java集合之ArrayList源码分析
ArrayList内部原理解析Header源码分析Footer
Header 之前讲了 HashMap 的原理后,今天来看一下 ArrayList 。 ArrayList 也是非常常用的集合类。它是有序的并且可以存储重复元素的。 ArrayList 底层其实就是一个数组,并且会动态扩容的。 源码分析 构造方法 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { // 创建初始容量的数组 this.elementData = new Object[i
俞其荣
2018/05/21
6950
从源码上分析 ArrayList
前言 ArrayList 是 List 接口的一个实现类,那么 ArrayList 的底层是如何实现的呢?让我们来一探究竟。 源码分析 属性 先来看看 ArrayList 中比较重要的两个属性: transient Object[] elementData; private int size; elementData 用来存储 ArrayList 中的元素,其实 ArrayList 的底层是用 Object[] 数组来实现的。 size 指的是的逻辑长度,就好像一个水杯,容量是 600 毫升,但杯中
一份执着✘
2018/06/04
4140
《JavaSE-第十六章》之ArrayList源码与扩容机制
ArrayList底层是一个Object数组,而数组在内存是连续的空间,所以使用ArrayList存储的元素与添加时的顺序是一致的,每一个ArrayList都有一个容量大小,当添加的元素数量大于该数组的容量时,ArrayList会自动扩容。
用户10517932
2023/10/07
2030
《JavaSE-第十六章》之ArrayList源码与扩容机制
聊聊ArrayList源码(基于JDK1.8)
打个广告,楼主自己造的轮子,感兴趣的请点[github]: https://github.com/haifeiWu/lightconf
haifeiWu
2018/09/11
3580
聊聊ArrayList源码(基于JDK1.8)
这可能是最细的ArrayList详解了!
# 手撕ArrayList源码 > 文章首发于GitHub开源项目: [Java超神之路](https://github.com/shaoxiongdu/java-notes) ## ArrayList 简介 ArrayList 是一个数组列表。它的主要底层实现是`Object`数组,但与 Java 中的数组相比,它的**容量能动态变化**,可看作是一个动态数组结构。特别注意的是,当我们装载的是基本类型的数据 int,long,boolean,short,byte… 的时候,我们只能存储他们对应的包装
程序员阿杜
2021/09/11
9430
Java集合之ArrayList扩容机制
以无参数构造方式创建ArrayList时,实际上初始化赋值的是一个空数组(public ArrayList())。当真正对数组进行添加元素操作时,才真正分配容量。即向数组中添加第一个元素时,数组容量扩为10
全栈程序员站长
2022/09/06
2900
Java集合之ArrayList扩容机制
ArrayList源码学习
ArrayList是一种以数组实现的列表,而数组的优势在于有角标,因此查询的速度较快,是一种可以动态扩容的数组。我们着重了解添加、获取、替换、删除操作。
路行的亚洲
2020/07/17
4380
相关推荐
【数据结构】线性表 ( 线性表概念简介 | 顺序存储结构 / 链式存储结构 | 顺序存储结构 - 顺序表 List | 顺序表 ArrayList 源码分析 )
更多 >
LV.1
这个人很懒,什么都没有留下~
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验