Java Advanced----LinkedList source analysis

Source: Internet
Author: User
Tags addall prev

Today, when I saw the source code of LinkedList, I met a pit. I study the source, found that LinkedList is a straight-line list structure, but I search for information in Baidu, the source of this part of the analysis, all said LinkedList is a circular linked list structure. I struggled for a long time, thought I understand wrong, and finally found the results in Google: because I see the source code is 1.7 and Baidu came out almost all of the 1.6. And there is no corresponding explanation. After 1.7, Oracle made some optimizations for the LinkedList, optimizing the ring structure in 1.6 in order to have a straight-line list structure. Here to remind friends, look at the source code, must look at the version, some of the situation is a small change, some places may have big changes, this will only look more confused.

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


The basic structure of LinkedListI've been talking about chain tables before, what is a linked list? As the name implies, the list is like a chain, each link is connected to the back of a ring and the front of a link, so that when we need to find a link in this chain, as long as we can find any link in the chain, we can find the ring we need. If we look at a picture, we can understand it very well.
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 is also the core of LinkedList. Let's take a look at the difference between the LinkedList in jdk1.6 and the 1.7 direct structurefirst 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 is changed. understand the structure above, it will be much easier to analyze.

the construction method of LinkedListThe LinkedList consists of 3 global parameters,size holds the number of nodes in the current linked list. First is a reference to a node in the list. Last is a reference to the final node of the linked list.
There are two linkedlist constructed methods, one is a 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 whether the passed-in index value is within a reasonable range checkpositionindex (        index);        Converts the given collection object to an object array object[] A = C.toarray ();        int numnew = A.length;        If the array is empty, return False if (numnew = = 0) return.        The array is not empty node<e> pred, succ;            if (index = = size) {//construct method call, index = size = 0, enter this condition.            SUCC = null;        Pred = Last;            } else {//The list is not empty when called, and the node method returns the nodes object at the given index SUCC = (index);        pred = Succ.prev;            }//Iterate through the array and insert an array of objects into the node for (object o:a) {@SuppressWarnings ("unchecked") e E = (e) o; node<e> NewNode = new Node<> (Pred, E, null);            if (pred = = null) first = NewNode;            else Pred.next = NewNode;        pred = NewNode;            } if (succ = = null) {last = pred;//assigns the final node of the current list to the previous} else {//The list is not empty when the disconnected part is connected            Pred.next = SUCC;        Succ.prev = pred;        }//Record the current number of nodes size + = Numnew;        modcount++;    return true; }
to illustrate here, node is the inner private class of LinkedList, and its composition is simple, with only one method of construction.
    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, the reference of the successor node.
with the above instructions, let's look at the construction method of LinkedList.
This piece of code is still well understood. We can work with images to get a deeper understanding.This code is divided into 2 cases, one is the original linked list is empty, one is the original linked list has values. Let's see separately .the original value of the case


with the code to see, is not a lot of clear ideas? The original list is empty, it is better to do, the incoming collection object directly converted to an array, the first value of the arrays as the head node, that is head, after the order of the added can be. And it saves the action of changing the point of the original node.
to sum up the two methods, it can be summed up as follows: The NULL implementation of the non-parametric construction. A parameter constructs an incoming collection object, converts the object into an array, and connects the array to the end in the order of traversal, and the global variable first and last point to each of the lists.
analysis of partial methods of LinkedListAddfirst/addlast Analysislet's see the code .
    public void AddFirst (e e) {        linkfirst (e);    }    private void Linkfirst (E e) {        final node<e> f = first;        Final node<e> NewNode = new node<> (null, E, F); Create a new node, the successor of the new node points to the original head node, the original head node is moved backward one, the new node instead of the head node position. First        = 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 well understood.Add a new node, look at the method name can be known, is in the current list of the head plus a node, since it is the head node, then the first node of the predecessor is bound to be null, so this is also node<e> NewNode = new node<> (NULL, E , f); The reason for such writing. Then we point to the head node of the current list, then judge the previous head nodes, if the header is null before inserting the element, the element that is currently added is the first point, which is the head node, so the current situation is: the head node = the node just joined = Tail node. If the head node is not null before inserting the element, then it proves that the previous linked list has a value, then we simply point the successor of the newly added node to the original header, and the tail is not changed. In this way, the original head node becomes the second one. Have achieved our purpose.
AddLast method in the implementation is a addfirst is consistent, here is not to repeat. Interested friends can look at the source code.
in fact, the LinkedList in the Add series of methods are very similar, is to create a new node, change the point of the previous node of the relationship. That's all.
Getfirst/getlast Method Analysis
    Public E GetFirst () {        final node<e> f = first;        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 it. It's very simple.
Get Method AnalysisHere's a look at the node method it calls
    Public E get (int index) {    //verifies whether the given index value is within a reasonable range of        Checkelementindex (index);        Return node (index). Item;    }    node<e> node (int 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;        }    }
At first I was puzzled, what was this about? Later, I understand that the code to do is: to determine the given index value, if the index value is greater than the entire list of the length of half, then looking forward from the back, if the index value is less than the length of the entire list of the general, then the former look backward. This ensures that, regardless of the length of the list, the search can be found with a maximum of half the length of the list, greatly improving efficiency.
Removefirst/removelast Method Analysis
    Public E Removefirst () {        final node<e> f = first;        if (f = = null)            throw new Nosuchelementexception ();        Return Unlinkfirst (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 First        = next;        if (next = = null) last            = null;        else            next.prev = null;        size--;        modcount++;        return element;    }

Take off the head node, turn the original second node into the head node, change the direction of the Frist, if there is only one node left, after removing all the null.
for the other methods of LinkedList, it is generally packaged with the above methods, no other big changes.


Java Advanced----LinkedList source analysis

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.