ArrayList源码分析_JDK1.8.0_191

ArrayList JDK1.8.0_191


基于数组实现

允许null值

不是线程安全

Vector是ArrayList的线程安全版本


 

ArrayList的变量

transient Object[] elementData;


 ArrayList的方法

1.add():添加元素

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

2.grow():扩容

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
//扩容为原来的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1); 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); }

3.elementData():获取节点值

E elementData(int index) {
    return (E) elementData[index];
}

4.set():修改节点值

public E set(int index, E element) {
    rangeCheck(index);
//获取旧值 E oldValue
= elementData(index);
//修改为新值 elementData[index]
= element; return oldValue; }

5.remove():删除节点

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);
//使得被删除节点可以被GC elementData[
--size] = null; // clear to let GC do its work return oldValue; }

 

posted @ 2019-07-22 19:57  、、、、、、、  阅读(314)  评论(0编辑  收藏  举报