ArrayList和LinkedList源码中的重点关注点

1.ArrayList(最重要的操作是数组复制,扩容)

 通过Object[]来保存数据;

transient Object[] elementData;

1)构造器,参数Collection,直接把Collection转成Array

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;
}
}
2)扩容,如何保证oldCapacity != 0和newCapacity不大于Integer.MAX_VALUE
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);
}
3)克隆是浅克隆,引用的复制
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
4)subList,新建一个与此List内部相关的内部类SubList

2.LinkedList(双向链表实现,支持双端操作,可以用作队列,栈,注意点是:链表节点的添加和释放)
通过Node存储数据,数据区存储了first,last,用于操作链表
transient Node<E> first;
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;
}
}

核心方法是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;
}
}















猜你喜欢

转载自www.cnblogs.com/helloGodWorld/p/9990343.html