Home  >  Q&A  >  body text

Regarding the implementation issues of java collection LinkedList

public E removeLast() {
    final Node<E> l = last;
    if (l == null)
        throw new NoSuchElementException();
    return unlinkLast(l);
}

last is a member variable. Why not use it directly in the method, but assign it to a final local variable?

过去多啦不再A梦过去多啦不再A梦2674 days ago920

reply all(2)I'll reply

  • typecho

    typecho2017-06-23 09:16:09

    Looked at the code

        transient Node<E> last;

    last is transient, right? If you assign it to a local final variable, you don’t need to check the value every time you use last, right?

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-23 09:16:09

    Part of the reason is to ensure thread safety. Assuming that this method does not use the l variable but directly references the last member, then the judgment becomes if(this.last == null). If last is assigned to null immediately after passing the judgment, then the next sentence unlinkLast(this.last) will have an unknown result.

    reply
    0
  • Cancelreply