LinkedList源码

7次阅读

共计 1769 个字符,预计需要花费 5 分钟才能阅读完成。

1 说明

  1. LinkedList 是一个双向链表,继承看 List 接口和 Duque 接口。
  2. LinkedList 不是线程安全, 确保线程安全方法
 List list = Collections.synchronizedList(new LinkedList(...))

2 源码分析

2.1 静态内部类

LinkedList 是一个链表, 需要一个 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;
    }
}

静态内部类,该类不能直接访问 LinkedLIst 的非静态成员(属性和方法),因为 Java 的约束:静态方法不能直接访问非静态的成员。

2.2 add() 方法

往 == 链表尾部 == 添加元素,boolean 修饰,总是返回 true

public boolean add(E e) {linkLast(e);
    return true;
}

再看 linkLast(e) 方法

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++;
}

如果 l 为空,则表示链表为空,插入的元素作为列表的第一个元素。
last 是一个全局变量

transient Node<E> last;

然后相应的 size 也增加。size 也是一个全局变量

transient int size = 0;

这样的话就可以写个获取 size 的方法,所以的 size 的方法为

public int size() {return size;}

2.3 get() 方法

public E get(int index) {checkElementIndex(index); 
    return node(index).item;
}

==checkElementIndex(index)== 判断寻找的索引是否越界,如果越界则抛出异常。
==node(index).item== 通过方法取得 nod 对象,然后取得 item 的值。

Node<E> node(int index) {// assert isElementIndex(index);

    if (index < (size >> 1)) {
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

这里通过位运算找出寻找范围的中间值,如果小于中间值,则出链头开始寻找,否则从链尾往回寻找。值得借鉴。

2.4 toArray() 方法

将列表转成数组的一个桥梁方法

public Object[] toArray() {Object[] result = new Object[size];
    int i = 0;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    return result;
}

2.5 clear() 方法

此调用返回后,列表将为空

public void clear() {
    // Clearing all of the links between nodes is "unnecessary", but:
    // - helps a generational GC if the discarded nodes inhabit
    //   more than one generation
    // - is sure to free memory even if there is a reachable Iterator
    for (Node<E> x = first; x != null;) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}

可以利用该方法清空 list 列表,达到 list 多次复用的目的,减少内存花销

正文完
 0