
arrayList 非线程安全的
add(E e) 扩容机制
1 2 3 4 5 6 7
|
public boolean (E e) { ensureCapacityInternal(size + 1); elementData[size++] = e; return true; }
|
1 2 3 4 5 6 7 8
|
private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
|
原数组为空minCapacity=10,若不为空则minCapacity=size+1;
1 2 3 4 5 6 7 8
|
private void ensureExplicitCapacity(int minCapacity) { modCount++; if (minCapacity - elementData.length > 0) grow(minCapacity); }
|
1 2 3 4 5 6 7 8 9 10 11 12
|
private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
|
newCapacity = oldCapacity + (oldCapacity >> 1) 新的数组大小是原数组大小的1.5倍。若新数组大小小于minCapacity,新数组大小就等于minCapacity
1 2 3 4 5 6 7 8
|
private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
|
若数组大小超过int的最大值则抛出异常
add(int index, E element) 插入元素
1 2 3 4 5 6 7 8 9 10 11 12
|
public void (int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
|
remove(int index) 移除元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; return oldValue; }
|
近期评论