LinkedList源码分析

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
}
private static class Node<E> {//Node是一个双向链表
    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;
    if (l == null)//没有元素 把节点设置为头节点
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}
 
/**
 * Unlinks non-null first node f.
 */
private E unlinkFirst(Node<E> f) {//移除头节点
    // assert f == first && f != null;
    final E element = f.item;//节点内容
    final Node<E> next = f.next;头节点的下一个节点
    f.item = null;//清空元素
    f.next = null; // help GC//指控元素指向,让gc回收对象
    first = next;
    if (next == null)
        last = null;
    else
        next.prev = null;
    size--;
    modCount++;
    return element;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值