LinkedList
LinkedList使用示例
LinkedList <Integer> linkedList = new LinkedList <>();
linkedList.add(12);
linkedList.add(23);
linkedList.add(45);
Iterator <Integer> iterator = linkedList.iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.println(value);
}
具有特征
- 数据事插入有序的
- 数据是可以重复插入的
- 集合是可以存储null的
- 底层采用的数据结果是双向链表
研究LinkedList源码的思路
1.关注继承关系
LinkedList继承的源码:
public class LinkedList<E> extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
对上述代码解释:
- AbstractSequentialList 继承了 AbstractList 是对后者方法的实现,便于子类继承直接复用
- 该接口也实现了List接口 , 能够实现克隆 (Cloneable), 实现序列化(Serializable)
- 实现了Deque接口 而该接口是一个双端队列,LinkedList也是Queue接口实现类,而且可以借助于该队列实现队列,可以实现栈
2.属性和默认值
底层结构:
//定义了集合中数据的格式
transient int size = 0;
//头节点位置
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;
}
}
LinkedList底层是一个双向链表
3.构造方法
源代码如下:
//无参构造函数
public LinkedList() {
}
//通过Collection集合来实例化LInkedList的实例
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
4.常用方法的研究
- add添加元素
public boolean add(E e) {
linkLast(e);
return true;
}
void linkLast(E e) {
final Node<E> l = last;
//新构造node节点以链表的尾节点作为前驱,将新节点插入到链表的尾部,尾插法
final Node<E> newNode = new Node<>(l, e, null);
//将新节点作为尾节点
last = newNode;
if (l == null)
//当前插入的是第一个节点,first=last=newNode
first = newNode;
else
//当前链表上已经存在节点
l.next = newNode;
size++;
modCount++;
}
添加元素是采用尾将节点插入链表,将size+1
- remove:删除元素:
public boolean remove(Object o) {
//删除的元素判断是否为null,判断相等逻辑会不同 o==null? ==:equals
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
//删除双向链表的节点逻辑
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
本质上是双向链表的删除节点的过程
- get():获取节点元素
public E get(int index) {
//判断位置的合法性
checkElementIndex(index);
return node(index).item;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
//从链表中的位置index来找到节点Node
Node<E> node(int index) {
//通过二分查找来确定要查找元素的位置,在size/2前半部分,采用从前往后查找,否则,从后往前查找
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;
}
}
应用场景(ArrayList和LinkedList)
ArrayList使用在查询比较多场景,而LinkedList适用于插入删除比较多场景