Analyzing Java Collection "LinkedList" from source code

Source: Internet
Author: User
Tags prev

LinkedList is a double-ended linked list, he inherits the Abstractsequentailist order lists, implements the List,deque,cloneable, and serializable interface. Deque is a double-ended queue interface, LinkedList has the first and last of the record header, so we can operate on both sides of the queue. It also implements the cloneable and Serializeble interfaces, respectively, that implement the queue for copying and serialization.

The structure of the LinkedList nodes is:

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;        }    }
where LIn addition to the first and last two basic attributes, LinkedList also includes:

transient int size = 0;//The number of elements in the record collection//fields inherited from class java.util.AbstractListprotected transient int modcount = 0 ///fixed several times//when using iterator to operate

It records the next node and the second node. Many of the operations of LinkedList are done by calling the following function:

/* * Insert an element as a header node into the collection * */private void Linkfirst (E e) {final node<e> f = first;        Final node<e> NewNode = new node<> (null, E, F);        first = NewNode;        if (f = = null) last = NewNode;        else F.prev = NewNode;        size++;    modcount++;    }/* * Insert an element as a team footer in the collection * */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++;}        /** * Inserts an element before the specified node, where the specified node cannot be null */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++;}/** * Deletes the specified node value, specifying the node after the node as the head node, F cannot be null */private E Unlinkfirst (node<e> f) {//assert F = = fi        RST && 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; /** * Delete the specified node value, specify the node before the node as the tail node, F cannot be null */private E Unlinklast (node<e> l) {//assert L = = Las        T && l! = null;        Final E element = L.item;        Final node<e> prev = L.prev;        L.item = null; L.prev = null;        Help GC last = prev;        if (prev = = null) first = NULL;        else Prev.next = null;        size--;        modcount++;    return element;      }/** * Delete the specified node, x value cannot be null */E unlink (node<e> x) {//assert x! = null;  Final E element = X.item;        Final node<e> next = X.next;        Final node<e> prev = X.prev;        if (prev = = null) {first = next;            } else {prev.next = next;        X.prev = null;        } if (next = = null) {last = prev;            } else {next.prev = prev;        X.next = null;        } X.item = null;        size--;        modcount++;    return element; }

It is important to note that LinkedList can not operate in the time complexity of O (n), according to the index value to specify the location of the node, we first look at random access, modify, add, modify the Source:

Public E get (int index) {        checkelementindex (index);        Return node (index). Item;    } Public E Set (int index, E element) {        Checkelementindex (index);        Node<e> x = node (index);        E oldval = X.item;        X.item = element;        return oldval;    } public void Add (int index, E element) {        Checkpositionindex (index);        if (index = = size)            linklast (element);        else            Linkbefore (element, node (index));    } Public E Remove (int index) {        checkelementindex (index);        Return unlink (node (index));    }
The Checkxxxxindex (index) function is used to detect whether index is available, and we can see that each time the method is called, it calls the node () method at the bottom, and what about it?

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;        }    }
First determine whether index is closer to the opponent or the end of the team, and where to start the traversal. Therefore, the random access efficiency of LinkedList is O (n). So we're not going to call

while (Index < list.size ()) {    get (index++);}
To traverse the LinkedList, what to do when the linkedlist needs to be traversed, call Listiterator (), or descendingiterator (), or invoke Deque () that inherits from iterator;

Both Listiterator () and Descendingiterator () are operating on LinkedList's inner class Listitr, which implements Listiterator<e>.

Private class Listitr implements listiterator<e> {        private node<e> lastreturned; <span style= " White-space:pre "></span>//The last node returned        private node<e> next;<span style=" White-space:pre "> </span>//the        index        of the next operation's node private int nextindex;<span style= "White-space:pre" ></span>//next private int expectedmodcount = Modcount; <span style= "White-space:pre" ></span>//iterator the number of modifications when modcount! = Expectedmodcount will throw concurrentmodficationexception        //Method        ...}

As we can see, it records the information that points to the last node returned and the next operation node, so we use the following code for LinkedList traversal:

Listiterator<string> iterator = List.listiterator ();        while (Iterator.hasnext ()) {            iterator.next ()}
Because the Listiterator interface is implemented, it is also capable of add,set,previous,hasprevious and previousindex relative to iterator. It is also important to note that Listitr has a property Expectedmodcount property that is assigned to LinkedList Modcount, and that, in addition to the Listitr or Hasxxx method, the Xxxindex method is called. Will detect if Expectedmodcount equals modcount, not equal to throw an exception, so after calling LinkedList's Xxxxiterator () method, Should not be directly through the LinkedList method to operate the list and should directly use the Xxxxiterator method to operate.


Analyzing Java Collection "LinkedList" from source code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.