本文共 2821 字,大约阅读时间需要 9 分钟。
JDK 8引入的LinkedList是一个基于内部类Node的双向链表,实现了List、Deque等接口。本文将从数据结构、源码分析、核心方法以及实际应用等方面探讨LinkedList的技术细节。
LinkedList采用双向链表结构,每个节点包含以下成员:
双向链表具有如下特点:
next
指针(指向下一个节点),也有prev
指针(指向上一个节点)prev
指向null
,最后一个节点的next
指向null
LinkedList类继承自AbstractSequentialList,实现了List、Deque等接口。其核心源码包括:
public class LinkedList extends AbstractSequentialListimplements List , Deque , Cloneable, Serializable { transient int size = 0; transient Node first; transient Node last; private static class Node { E item; Node prev; Node next; Node(Node prev, E element, Node next) { this.prev = prev; this.item = element; this.next = next; } } public boolean add(E e) { linkLast(e); return true; } void linkLast(E e) { Node l = last; Node newNode = new Node<>(l, e, null); last = newNode; if (l == null) { first = newNode; } else { l.next = newNode; } size++; modCount++; } public E remove() { return removeFirst(); } private E removeFirst() { Node f = first; unlinkFirst(f); return f.item; } private E unlinkFirst(Node f) { Node next = f.next; f.prev = null; if (f == last) { last = next; } if (next != null) { next.prev = null; } size--; modCount++; return f.item; } // 其他核心方法包括`remove(int index)`、`remove(Object o)`、`removeFirstOccurrence(Object o)`、`removeLastOccurrence(Object o)`、`linkBefore()`等}
LinkedList继承结构:
LinkedList├── AbstractSequentialList│ └── AbstractList│ └── AbstractCollection└── Object
实现的接口包括:
LinkedList的增删方法采用了“快_delete”和“慢_delete”两种策略:
LinkedList提供6种重载的add
方法:
add(E e)
:默认在尾部添加add(int index, E e)
:在指定位置插入元素addAll(Collection<E>)
addAll(int index, Collection<E>)
addFirst(E e)
addLast(E e)
LinkedList提供7种重载的remove
方法:
remove()
remove(int index)
remove(Object o)
removeFirst()
removeLast()
removeFirstOccurrence(Object o)
removeLastOccurrence(Object o)
LinkedList提供的get
方法包括:
get(int index)
getFirst()
getLast()
indexOf(Object o)
:从头到尾查找lastIndexOf(Object o)
:从尾到头查找LinkedList支持浅行拷贝:
public Object clone() { LinkedListclone = new LinkedList<>(); clone.first = null; clone.last = null; clone.size = 0; clone.modCount = 0; for (Node x = first; x != null; x = x.next) { clone.add(x.item); } return clone;}
LinkedList作为Java Collections家族的一员,凭借其双向链表架构,在数据存储与操作方面展现出独特优势。尽管其随机访问效率低于数组实现,但在灵活性和快速操作方面做到了极致。对于需要经常操作列表两端的应用场景, LinkedList 是一个理想的选择。
转载地址:http://ykwfk.baihongyu.com/