Java集合(一)ArrayList的扩容机制

(Java1.8 ArrayList源码)

1. 首先看一下ArrayList中声明的变量

    /**
     * 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.
     * 【用于默认大小的空实例的共享空数组实例。我们将它和EMPTY_ELEMENTDATA区别开来,以便于知道当第一个元素添加进来时,他扩张了多少】
     */
    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.
     * 【被储存的ArrayList元素的数组缓冲区。这个数组缓冲区的长度就是ArrayList的容量。当添加第一个元素时,任何带有elementData==DEFAULTCAPACITY_EMPTY_ELEMENTDATA属性的空ArrayList都会被扩充成DEFAULT_CAPACITY(默认容量即10)】
     */
    transient Object[] elementData; // non-private to simplify nested class access

    /**
     * The size of the ArrayList (the number of elements it contains).
     * 【ArrayList的大小(它包含的元素数量)】
     *
     * @serial
     */
    private int size;
复制代码

2. 再来看它的构造器函数

 /**
     * Constructs an empty list with the specified initial capacity.
     * 【构造一个带有指定初始容量的空列表】
     *
     * @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);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     * 【构造一个初始容量为10的空列表】
     */
    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) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
复制代码

3. 代码实现---查看ArrayList的扩容效果

因为ArrayList通过elementData对象数组来储存数据,所以这个数组的长度就是ArrayList的大小。而在开头的声明变量中看到这个参数是private,所以需要反射才能得到。

package cn.wh3t;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class Main {

    public static Integer getCapacity(ArrayList list){
        Integer length = null;
        Class<?> clazz = ((Object) list).getClass();
        Field field;
        try {
            field = clazz.getDeclaredField("elementData");
            field.setAccessible(true);

            Object[] objects = (Object[]) field.get(list);
            length = objects.length;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return length;
    }

    public static void main(String[] args) {
	// write your code here
        ArrayList<Integer> arrayList = new ArrayList<>();
        Integer capacity = getCapacity(arrayList);
        int size = arrayList.size();
        System.out.println("容量:"+capacity);
        System.out.println("大小:"+size);
    }
}
复制代码
容量:0
大小:0
复制代码

添加一个元素

package cn.wh3t;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
	// write your code here
        ArrayList<Integer> arrayList = new ArrayList<>();

        arrayList.add(1);

        Integer capacity = getCapacity(arrayList);
        int size = arrayList.size();
        System.out.println("容量:"+capacity);
        System.out.println("大小:"+size);
    }
}
复制代码
容量:10
大小:1
复制代码

添加11个元素

package cn.wh3t;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
	// write your code here
        ArrayList<Integer> arrayList = new ArrayList<>();

        for (int i = 0;i<11;i++){
            arrayList.add(i);
        }

        Integer capacity = getCapacity(arrayList);
        int size = arrayList.size();
        System.out.println("容量:"+capacity);
        System.out.println("大小:"+size);
    }
}
复制代码
容量:15
大小:11
复制代码

所以容量变为15,即1.5倍

    /**
     * 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);
            //如果ArrayList为空,那么minCapacity取minCapacity和10的最大值
        }
        //此处minCapacity为size+1
        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
            //minCapacity大于ArrayList的大小则扩容
    }
复制代码
    /**
     * 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);
        //此处新的容量= 旧容量+旧容量>>1(右移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);
        //最后完成数据复制
    }
复制代码

参考链接:
ArrayList动态扩容机制--源码解析

转载于:https://juejin.im/post/5d0c85e06fb9a07ee0631f02

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值