ArrayList
Arraylist数据结构:
数组 Object[] EMPTY_ELEMENTDATA
ArrayList初始长度:10
ArrayList扩容:
数组默认长度为10,重新创建一个新的数组,并将原始数据执行Arrays.copyOf(),每次扩容1.5倍长度
private void add(E e, Object[] elementData, int s) { if (s == elementData.length) elementData = grow(); elementData[s] = e; size = s + 1; } //2 将原数组的内容copy到新的数组中 private Object[] grow(int minCapacity) { return elementData = Arrays.copyOf(elementData, newCapacity(minCapacity)); } //1 创建一个新的数组,长度为原来的1.5倍 private int newCapacity(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity <= 0) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) return Math.max(DEFAULT_CAPACITY, minCapacity); if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return minCapacity; } return (newCapacity - MAX_ARRAY_SIZE <= 0) ? newCapacity : hugeCapacity(minCapacity); }
ArrayList删除元素:
public E remove(int index) { // 索引index是否在数组长度范围内 Objects.checkIndex(index, size); final Object[] es = elementData; @SuppressWarnings("unchecked") E oldValue = (E) es[index]; fastRemove(es, index); return oldValue; } //删除元素,需要改元素后面的元素都向前移动一个位置 private void fastRemove(Object[] es, int i) { modCount++; final int newSize; if ((newSize = size - 1) > i) System.arraycopy(es, i + 1, es, i, newSize - i); //元素置为null es[size = newSize] = null; }