看源码:
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { transient int size = 0; /** * 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; /** * Constructs an empty list. */ public LinkedList() { }翻译一下这个类的描述,双向链表列表实现了List和Deque接口,实现了List的所有方法和允许所有的元素。 对于双向链表列表而言,所有的操作都是这样执行的,从头开始遍历,当找到指定的索引后,关闭列表。 特别强调一下,LinkedList不是线程安全的等等。好了,不看了,直接看实现吧,学过数据结构的都知道双向链表的实现,应该还都是pascle的代码吧,现在看看java的实现。
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; } }是一个静态内部类,我们刚说过静态内部类用的不多,没想到这么快就在这里见到了,定义了内容,下一个节点,上一个节点,三个属性和一个构造函数。 双向链表在最后增加新元素: /** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ public boolean add(E e) { linkLast(e); return true; } /** * Links e as last element. */ void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; // 新创建的节点指向last变量 if (l == null) // 如果是第一个节点 first = newNode; //新创建的节点指向first else l.next = newNode; // 原节点的下一个节点指向新创建的节点 size++; modCount++; }双向链表在指定index增加新元素,先看图,了解一下操作:
再看代码:
/** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any * subsequent elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted * @param element element to be inserted * @throws IndexOutOfBoundsException {@inheritDoc} */ public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } /** * Inserts element e before non-null Node succ. */ void linkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ); succ.prev = newNode; if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; }就是简单的链表操作,理解了LinkedList的实现,我们对这个类应该有点了解了,双向链表适合修改数据效率高。