=========================================================
ArrayList是实现了基于动态数组的数据结构:(源码)
transient Object[] elementData;
LinkedList基于链表的数据结构:(源码)
transient Node<E> first;
transient Node<E> last;
============================================================
ArrayList&LinkedList都实现了List接口
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
}
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
}
==============================================================
ArrayList添加元素的过程:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 确保对象数组elementData有足够的容量,可以将新加入的元素e加进去
elementData[size++] = e;//加入新元素e,size加1
return true;
}
/**
* 确保数组的容量足够存放新加入的元素,若不够,要扩容
*/
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;//获取数组大小(即数组的容量)
//当数组满了,又有新元素加入的时候,执行扩容逻辑
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3) / 2 + 1;//新容量为旧容量的1.5倍+1
if (newCapacity < minCapacity)//如果扩容后的新容量还是没有传入的所需的最小容量大或等于(主要发生在addAll(Collection<? extends E> c)中)
newCapacity = minCapacity;//新容量设为最小容量
elementData = Arrays.copyOf(elementData, newCapacity);//复制新容量
}
}
LinkedList添加元素的过程:
//Appends the specified element to the end of this list.
2 public boolean add(E e) {
3 linkLast(e);
4 return true;
5 }
6 /**
7 * Links e as last element.
8 */
9 void linkLast(E e) {
10 final Node<E> l = last;
11 final Node<E> newNode = new Node<>(l, e, null);
12 last = newNode;
13 if (l == null)
14 first = newNode;
15 else
16 l.next = newNode;
17 size++;
18 modCount++;
19 }
本文深入解析了ArrayList与LinkedList两种Java集合类的实现原理,对比了它们的数据结构特点,详细介绍了这两种集合类如何进行元素的添加操作,并分析了背后的扩容机制与链表节点链接过程。

3200

被折叠的 条评论
为什么被折叠?



