Java 容器
5. LinkedList
5.1 概览
基于双向链表实现,使用 Node 存储链表节点信息。
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;
}
}
每个链表存储了 first 和 last 指针:
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
5.2 与 ArrayList 的比较
- ArrayList 基于动态数组实现,LinkedList 基于双向链表实现;
- ArrayList 支持随机访问,LinkedList 不支持;
- LinkedList 在任意位置添加删除元素更快。
本文深入探讨了Java中LinkedList的内部实现机制,包括基于双向链表的结构和Node类的定义,对比了LinkedList与ArrayList的不同之处,如随机访问的支持、元素添加和删除的效率等。
526

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



