Java Advanced----LinkedList source code Analysis __java

Source: Internet
Author: User
Tags addall prev static class

Today, while looking at the source code of LinkedList, I met a hole. I study the source, found LinkedList is a straight line of the linked list structure, but I search data in Baidu, about this part of the source code analysis, all said LinkedList is a ring-linked list structure. I struggled for a long time, I think I understand the wrong, and finally found the results in Google: because I see the source code is 1.7 and Baidu came out almost all are 1.6. And there is no corresponding description. After 1.7, Oracle made some optimizations for the LinkedList, and optimized the ring structure in 1.6 for a straight-line linked-list structure. Here to hint friends, look at the source, must see the version, some of the situation is small changes, and some places may have big changes, so only the more confused.

Okay, here we are. Let's analyze some source code of LinkedList in Java. (This article is for 1.7 of the source code)


the basic structure of LinkedList I've been talking about chain tables, and that's what a linked list is. As the name suggests, the list is the same as the chain, each with a link to the back and the front, so that when we need to find a link to the chain, we can find the one that we need as long as we can find the link in the chain. If we look at a picture, we can get a good understanding of it.
In LinkedList, we call the "ring" of the Chain "node", and each node is the same structure. The connection between nodes and nodes constitutes the basic data structure of our linkedlist, and also the core of LinkedList. Let's take a look at the difference between the jdk1.6 and 1.7 direct structure of the LinkedList first look at the structure in 1.7

And look at the structure in 1.6.
By contrast, you know where the difference is. In 1.7, the ring structure is removed, and the natural part of the code changes. Understand the structure above, it will be much easier to analyze.

the construction method of LinkedList The LinkedList contains 3 global parameters, and size holds the number of nodes in the current list. First is a reference to the node in the list. A reference to the last node of the linked list.
There are two LinkedList construction methods, one is the parameterless construct, and the other is the construction of the incoming collection object.

    Nothing to do, is an empty implementation public LinkedList () {} public linkedlist (collection<? extends e> c) {This
        ();
    AddAll (c);
    public boolean AddAll (collection<. extends e> c) {return AddAll (size, c); public boolean addall (int index, COLLECTION&LT;? extends e> c) {//check that the incoming index value is within reasonable bounds Checkpositioni
        Ndex (index);
        Converts the given collection object to an object array object[] A = C.toarray ();
        int numnew = A.length;
        Returns False if (numnew = = 0) return False if the array is empty;
        Array is not empty node<e> pred, succ;
            if (index = = size) {//constructor method call, index = size = 0, enter this condition.
            SUCC = null;
        Pred = Last;
            else {//list is not empty, the node method returns the nodes object at the given index location SUCC = Nodal (index);
        pred = Succ.prev;
            ///traversal array, insert the object of the array into the node for (object o:a) {@SuppressWarnings ("unchecked") E = (e) o; Node<e> NewNode = new Node<> (pred, E, NULL);
            if (pred = = null)-NewNode;
            else Pred.next = NewNode;
        pred = NewNode; 
            } if (succ = = null) {last = pred;///////////////() The disconnected part is connected to the end of the.} else {//list Non-empty
            Pred.next = SUCC;
        Succ.prev = pred;
        //Record the current number of nodes = numnew;
        modcount++;
    return true; }
To illustrate, node is the internal private class of LinkedList, and its composition is simple, with only one construction method.
    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;
        }
    
The parameter order of the constructor method is: the reference of the preceding node, the data, and the successor node.
With the instructions above, let's look at how the LinkedList is constructed.
This piece of code is very well understood. We can cooperate with the picture to understand deeply. This code is divided into 2 kinds of cases, one is the original linked list is empty, one is the original linked list has a value. Let's look at the original value, respectively.



With the code to see, is not the idea of a lot of clarity. The original linked list is empty words will be better to do, directly to the incoming collection object into an array, the first value of the arrays as the head node, that is, heads, after the order to join in. and saves the operation that the original node points to.
To sum up with two kinds of construction methods, it can be summarized as follows: The parameterless construct is an empty implementation. A parameter constructs an incoming collection object, converts the object to an array, and ends the array in the order of traversal, and the global variable first and last point to this list, respectively.
LinkedList Part Method Analysis Addfirst/addlast AnalysisLet's look at the code.
    public void AddFirst (e e) {
        linkfirst (e);
    }

    private void Linkfirst (E e) {
        final node<e> f = i;
        Final node<e> NewNode = new node<> (null, E, F); Create a new node, the successor of the new node point to the original head node, the original head node to move backward one bit, the new node instead of the location of the head nodes. I
        = NewNode;
        if (f = = null) Last
            = NewNode;
        else
            f.prev = NewNode;
        size++;
        modcount++;
    }
In fact, as long as you understand the data structure above, this code is very good to understand. Join a new node, look at the method name can know, is in the current list of the head plus a node, since it is the head node, then the head node of the former must be null, so this is also node<e> NewNode = new node<> (null, E, F); The reason for this writing. Then first points to the head node of the current list, before the first node to judge, if the insertion of elements before the header is null, then the current element is the first point, that is, the head node, so the current situation is: head node = just join the node = Tail node. If the header node is not null before inserting the element, then the previous linked list is valued, then we only need to point the successor of the newly added node to the original head node, and the tail is not changed. As a result, the original header node becomes the second one. achieved our purpose.
AddLast method in implementation is a addfirst is consistent, here is not to repeat. Interested friends can look at the source code.
In fact, the method of the Add series in LinkedList is similar, is to create a new node, change the previous node's point of relationship. That's all.
Analysis of Getfirst/getlast method
    Public E GetFirst () {
        final node<e> f = i;
        if (f = = null)
            throw new Nosuchelementexception ();
        return f.item;
    }

    Public E-GetLast () {
        final node<e> l = last;
        if (L = = null)
            throw new Nosuchelementexception ();
        return l.item;
    }
This code does not need to parse the bar. It's simple.
Get Method AnalysisHere's a look at the node method it calls
    Public E get (int index) {
    	//Verify that the given index value is checkelementindex within a reasonable range
        (index);
        Return node (index). Item;

    node<e> node (int index) {
        if (Index < (size >> 1)) {
            node<e> x = i;
            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;
        }
    }
At first I was puzzled, this is what to do. Later I realized that the code to do is: to determine the given index value, if the index value is greater than half the length of the entire chain, then look forward, if the index value is less than the length of the entire list of the general, then look back. This ensures that no matter how large the length of the list, search can be found at most only half the length of the list, greatly improving the efficiency.
Analysis of Removefirst/removelast method
    Public E Removefirst () {
        final node<e> f = i;
        if (f = = null)
            throw new Nosuchelementexception ();
        Return Unlinkfirst (f);
    }

    Private E Unlinkfirst (node<e> f) {
        //assert F = = i && f!= null;
        Final E element = F.item;
        Final node<e> next = F.next;
        F.item = null;
        F.next = null; Help GC-I
        = next;
        if (next = null) last
            = null;
        else
            next.prev = null;
        size--;
        modcount++;
        return element;
    }

Remove the head node, the original second node into a head node, change the point of Frist, if only one node left before, removed all to null.
Other methods for LinkedList are generally packaged with these methods, with no major changes.


Related Article

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.