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. */ 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;//ArrayList实际数据的数量
三个构造器主要目的是初始化Object[] 的长度
1、ArrayList(),默认构造数组长度为10空列表,但是DEFAULTCAPACITY_EMPTY_ELEMENTDATA长度我们并不知道,真正设置数组长度是在add()方法扩容时候设置
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
2、new Array(),指定数组长度的列表,这个构造器的优点是如果我们知道数据的大小,初始化时指定长度则会减少数组扩容的次数,大大提高ArrayList的效率
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); } }
3、new ArrayList(Collection c),这个构造器是可以把其它实现Collection接口的类当做参数,构造Object[]
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; } }
ArrayList-add
1、add(E e)
/** * 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);//DEFAULT_CAPACITY默认是10,Math.max 取最大值
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) { modCount++;//modCount 数组修改次数 ,无论add remove 都会++ // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }