ArrayList和linkedlist的add方法
- ArrayList和linkedlist都继承Collection和List接口.
Arraylist
transient Object[] elementData;
// non-private to simplify nested class access(非私有以简化嵌套类访问)
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
add方法,总是返回true。
用数组elementData来保存,在此数组中保存至最后。
LinkList
public boolean add(E e) {
linkLast(e);
return true;
}
也总是返回true。在linkLast中实现的是链表
List内部实现的双链表,lsat是最末位的元素,linkLast把元素连接到末位。
/**
* Links e as last element.链接e作为最后一个元素。
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}