·  阅读 65

1. ArrayList 底层基于数组实现

get(int index) 获取元素，基于内存地址获取，速度很快 add(Object element) 在数组尾部增加一个元素 add(int index,Object element) 在数组中某个位置增加一个元素 remove(int index) 删除数组中的某个位置的元素 set(int index,Object element) 替换数组中某个位置的元素

``````private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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);
}

``````System.arraycopy(elementData, index, elementData, index + 1,size - index);

transient这个关键字是指不参与序列化

``````/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
*            (first.prev == null && first.item != null)
*/
transient Node<E> first;

/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
*            (last.next == null && last.item != null)
*/
transient Node<E> last;

``````private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;

Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}

next指向后面node的指针,prev指向前面node的指针

``````linkBefore(element, node(index));

Node<E> node(int index) {
// assert isElementIndex(index);

if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}

``````void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}

get(int index)其实就是node(int index) 通过遍历获取结点。可见get操作需要通过遍历来获取，性能不如ArrayList通过内容地址获取

``````public E get(int index) {
checkElementIndex(index);
return node(index).item;
}