一、Java 集合框架
Java 集合框架是存储和操作对象的核心体系,主要分为 Collection(单列) 和 Map(双列)。
Collection 接口体系
- 根接口:
Collection定义了增删改查、遍历等基础操作。 - 子接口:
List:有序且可重复。Set:无序且不可重复。Queue:队列结构。
Map 接口体系
- 存储键值对(Key-Value),Key 唯一。
- 子接口如
SortedMap支持按键排序。
本文重点聚焦于 List 接口的实现类之一:LinkedList。
二、链表数据结构
在底层数据结构中,链表通过非连续的内存单元存储元素。理解其节点构成有助于掌握 Java 中的实现逻辑。
- 节点(Node):基本存储单元,包含数据域(业务数据)和指针域(指向下一个或上一个节点的引用)。
- 头指针:指向链表第一个节点的入口引用。
- 尾节点:最后一个节点,单向链表中通常指向
null。
三、手动实现单链表
为了深入理解原理,我们可以尝试手写一个无头结点的单向链表。这有助于理清增删操作的边界条件。
1. 节点定义
static class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
2. 核心方法实现
这里展示几个关键操作,实际开发中建议直接复用 JDK 提供的工具类,但理解源码逻辑至关重要。
创建与插入
ListNode head;
// 头插法:O(1)
public void addFirst(int data) {
ListNode node = new ListNode(data);
node.next = head;
head = node;
}
// 尾插法:需遍历至尾部 O(n)
public void addLast(int data) {
ListNode node = new ListNode(data);
if (head == null) {
head = node;
return;
}
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
// 指定位置插入
public void addIndex(int index, int data) {
if (index < 0 || index > size()) {
System.out.println("index 不合法");
return;
}
if (index == 0) {
addFirst(data);
return;
}
if (index == size()) {
addLast(data);
return;
}
// 找到 index-1 位置的节点
ListNode prev = findIndex(index - 1);
ListNode node = new ListNode(data);
node.next = prev.next;
prev.next = node;
}
private ListNode findIndex(int index) {
ListNode cur = head;
int count = 0;
while (count != index) {
cur = cur.next;
count++;
}
return cur;
}
删除与查找
// 删除第一次出现的 key
public void remove(int key) {
if (head == null) return;
if (head.val == key) {
head = head.next;
return;
}
ListNode prev = head;
while (prev.next != null && prev.next.val != key) {
prev = prev.next;
}
if (prev.next != null) {
prev.next = prev.next.next;
}
}
// 获取长度
public int size() {
int count = 0;
ListNode cur = head;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
四、LinkedList 官方 API
JDK 中的 LinkedList 基于双向链表实现,相比上述单向链表,它支持首尾双向操作。
1. 构造方式
// 空链表
LinkedList<Integer> list = new LinkedList<>();
// 基于集合初始化
List<Integer> source = new ArrayList<>();
LinkedList<Integer> list2 = new LinkedList<>(source);
2. 核心特性
- 双端队列:实现了
Deque接口,支持栈(LIFO)和队列(FIFO)行为。 - 随机访问:通过索引访问效率较低(O(n)),因为需要遍历。
- 增删效率:在已知节点附近操作效率高(O(1)),无需移动元素。
3. 常用方法对比
| 操作 | 方法示例 | 说明 |
|---|---|---|
| 队尾入队 | add(e) / offer(e) | 等价于 addLast |
| 队首出队 | poll() | 等价于 removeFirst |
| 栈顶入栈 | push(e) | 等价于 addFirst |
| 栈顶出栈 | pop() | 等价于 removeFirst |
五、遍历方式
1. 增强 for 循环
最简洁的方式,底层依赖迭代器。
for (Integer x : list) {
System.out.print(x + " ");
}
2. 迭代器 Iterator
适合需要修改集合结构的场景。
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer val = iterator.next();
// 处理逻辑
}
3. ListIterator
支持双向遍历,可在遍历时修改元素。
ListIterator<Integer> lit = list.listIterator();
while (lit.hasNext()) {
System.out.print(lit.next() + " ");
}
总结
LinkedList 适合频繁在头部或中间进行插入删除的场景,但不适合大量随机读取。在实际工程中,若主要涉及顺序访问,ArrayList 往往性能更优;若需模拟队列或栈的行为,LinkedList 提供了便捷的 API 支持。

