Home > OS >  In Java LinkedList source code, why the unlinkFirst function should have a param pointing to the fir
In Java LinkedList source code, why the unlinkFirst function should have a param pointing to the fir

Time:10-15

Some part of the source code in LinkedList, which contains all of the reference to the unlinkFirst function:

    /**
     * Pointer to first node.
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    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
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount  ;
        return element;
    }

    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

I think that using a non-param function like this:

    private E unlinkFirst() {
        Node<E> f = first;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount  ;
        return element;
    }

is easier to read and more convinient to call.So what's the intention to write like that?

CodePudding user response:

The method for removing the first Node from a List can be implemented to be parameterless, and duplicating the reference to the first node might seem redundant.

I think it's done for the purpose of consistency, to make internal all methods which are meant for Node-removal adhere with same stylistic patterns.

Method romove() delegates to the auxiliary method unlink(Node<E> x) (in this case the link to the target node is required), and similarly romoveFirst() delegates to unlinkFirst(Node<E> f), removeLast() delegates to unlinkLast(Node<E> l).

All three unlink, romoveFirst and unlinkLast are meant to be used internally, all are implemented to dial with only non-null nodes. There's no necessity romoveFirst and unlinkLast to expect the node as an argument, it's rather a stylistic choice.

  •  Tags:  
  • java
  • Related