集合-ArrayList 源码解读-01

ArrayList 我们都知道底层是使用 数组(线性表)来存储元素的。我们就来简单的分析一下 ,它是如何动态扩容的。

// 构造函数
List list  = new ArrayList();
list.add(1);// 添加一个元素。

我们就从这两句代码开始。

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
  /**
     * Default initial capacity.
     */
    private static final int DEFAULT_CAPACITY = 10;
// initialCapacity 默认是10 
 /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};
   public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity]; // 初始化Object 数组 
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA; // 初始容量为0 的话,就是默认空数组。
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
}
 /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

我们看到 ArrayList 集合是采用 Object 数组来存储的数据。创建时我们可以传入 数组容量大小,没有传入的话 就是一个空数组。

  • 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;
    }

往集合里面 添加一个元素,首先 重新确定 集合 大小 ensureCapacityInternal(size + 1);,然后 将元素 elementData[size++] = e; 加入到 数组中。注意这里是线程非安全的。我们再来看看 它底层是如何计算 数组容量的。

  • ensureCapacityInternal(size + 1); //size 默认等于 0
private void ensureCapacityInternal(int minCapacity) { // minCapacity = 0+1;
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 空数组的情况下
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); // 容量去 两者的最大值。这里就是 10
        }

        ensureExplicitCapacity(minCapacity);  // 10 
    }

 private void ensureExplicitCapacity(int minCapacity) {
        modCount++; // 计数器

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity); //动态计算容量,当前 minCapacity  = 10
    }


    /**
     * 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); // 新的值 = 旧的值 + 旧的值/2 (1.5 倍)
        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); //复制 原来 数组中的 元素 到 到新的元素中去。
    }
  • elementData = Arrays.copyOf(elementData, newCapacity);
    /**
     * 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 <tt>null</tt>.
     * Such indices will exist if and only if the specified length
     * is greater than that of the original array.
     * The resulting array is of exactly the same class as the original array.
     *
     * @param <T> the class of the objects in the array
     * @param original the array to be copied
     * @param newLength the length 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 <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }

  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;
    }
  • System.arraycopy(original, 0, copy, 0,
    Math.min(original.length, newLength)); 复制 原来的数组到 新的数组中。
    original :原来的数组 值
    第一个 0 : 复制开始的角标, 从0 开始
    copy: 复制到目标数组
    第二个0 : 目标数组中开始 保存数据的脚本 ,从0 开始
    Math.min(original.length, newLength) :需要复制的元素的个数。
// 本地方法栈中的数据
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

上面的逻辑 完成了以下的事情:

  1. 当新添加数据是,重新计算 object 数组的大小,默认是 10 ,当容量超过10 后 ,会扩容为 15 (1.5 倍)
  2. 复制原来数组中的数据 到新的数组中,更新数组变量引用。

我们再回过头来看看这个代码:

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e; 
        return true;
    }
  • elementData[size++] = e; 添加新元素到 Object[] 中,同时 size++ 。

上面这句话就完成了 一个元素 添加到 Object[]中 。

  • 从上面代码也能分析出,在ArrayList 中 元素是有序存储的,新添加的元素总是在 集合的最后面。下面我们看看 在 指定的位置 插入 元素是怎么一回事。

我们从 线性表-数组的存储结构上看,在一个数组中 插入一个元素 是要移动 原来 元素的位置的,我们就来分析下,java 是怎么玩的

  public void add(int index, E element) {
        rangeCheckForAdd(index);
// 这句话 动态的扩容后 ,还将原来数组中的数据复制到了新的数组中。
        ensureCapacityInternal(size + 1);  // Increments modCount!!
// 这句话就是 将 index 后面包括 index 所在的元数 向后 移动一位,留出 位置。        
      System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;  // 将元数 写入 index 位置
        size++; // size 自增 
    }

我们发现 java 中 移动 元数 是 调用 本地方法栈中的方法。

上面我们分析了 两种add 方法,步骤都差不多,核心就是 动态扩容后,会将原来的 数据 复制到 新的object[] 中。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容