1.是什么?
LinkedList 是一个双向链表结构的集合,非线程安全。
2.主要属性
transient int size = 0;
:表示集合的元素个数transient Node<E> first;
:指向第一个元素transient Node<E> last;
:指向最后一个元素
3.节点的定义
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;
}
}
4.新增方法
// 将新增元素放在队尾
public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
①第一次新增
first
属性和last
属性都指向第一个节点,节点的指向前一个节点属性和指向后一个节点属性为null
②第X次新增
first
属性指向第一个节点,第一个节点的指向前一个节点属性为null,中间都是双向链接结构进行连接。last
属性指向最后一个节点,最后一个节点的指向后一个节点的属性为null
5.获取方法
①获取第一个元素
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
②获取最后一个元素
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
6.移除元素
①移除第一个元素
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
②移除最后一个元素
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}