JDK1.8 source Code (II)--java.util.linkedlist

Source: Internet
Author: User

LinkedList definition LinkedList is a linear table (doubly linked list) that is implemented by a linked list, and the elements are ordered and can be duplicated.
 Public class Linkedlist<e>    extends abstractsequentiallist<e>    implements List<e> Deque<e>, Cloneable, java.io.Serializable

Blue solid Arrows refer to class inheritance relationships

Green solid arrow refers to the interface inheritance relationship

The green dashed arrow refers to the interface implementation relationship

The LinkedList inherits the Abstractsequentiallist and implements the list and deque,cloneable, serializable interface.

, implementing the List interface

  The List interface defines a set of methods that the classes that implement the interface must implement, as shown below, and we'll cover the implementation of this series of methods in more detail.

Field Properties
// number of linked list elements (nodes) transient int size = 0; // A pointer to the first element transient node<e> first ; // A pointer to the last element transient Node<e> last;
View Code

  Notice there is a node class, which is an inner class in the LinkedList class, and each element in the collection represents a node class object, and the LinkedList collection is made up of many node objects similar to hand pulls, so LinkedList is a doubly linked list.

 private  static  class  node<e> {E item;  //     store business data  Node<e> Next; //     is a reference to the previous node of the node  Node<e> prev; //  is a reference to the next node of the node   node (node  <E> prev, E element, node<e>  next)        { this . Item = this . Next = next;     this . Prev = prev; }}
View Code

: Each node prev a reference to the previous node, and next holds a reference to the next node;

Note: The first node prev does not point to the node, NULL, and the last node next does not point to the node, also null

constructor function

①, non-parametric constructors

 Public LinkedList () {}

Note: There is no need to initialize the size of the linked list, unlike ArrayList, which needs to initialize the size of the array to add elements

②, generic parameter with parameter constructor

 Public extends E> c) {    this();    AddAll (c);}

Add an instance of the collection collection of an existing element to the LinkedList, as described in detail below

adding elements

①,Add (E E)

 Public BooleanAdd (e e) {//add an element to the end of a linked listLinklast (e); return true;}voidLinklast (e e) {FinalNode<e> L = last;//use variables to store linked list tail nodes first    FinalNode<e> NewNode =NewNode<> (L, E,NULL);//add a new element, you need a new node, the element content is E,prev is the address reference of the current last node, Next is nulllast = NewNode;//point the tail of the list to the new node    if(L = =NULL) First= NewNode;//If the list is empty, the new node is also set as the head node, then the new node is both the head node and the tail node, and the Prev and next of the head node are null    ElseL.next= NewNode;//The linked list is not empty, which points to the new node of the trailing node of the original linked list that was previously storedsize++;//number of nodes plus 1modcount++;//prevents the addition of elements when set traversal, as in ArrayList}
View Code

It is important to note that if the list is empty, the pointer to the first element and the pointer to the last element point to the current node

②,AddFirst (e E)

 Public voidAddFirst (e e) {Linkfirst (e);}Private voidLinkfirst (e e) {FinalNode<e> f = First;//Store the linked list head node with the variable F first    FinalNode<e> NewNode =NewNode<> (NULL, E, F);//constructs the specified element as a new node with an element content of E,prev to Null,next as the address reference for the current first node ,first = NewNode;//point the list head to the new node    if(f = =NULL) Last= NewNode;//If the list is empty, the new node is also set as the tail node, then the new node is both the head node and the tail node    ElseF.prev= NewNode;//If the linked list is not empty, the previous node of the head node F of the original linked list points to the new nodesize++;//number of nodes plus 1modcount++;//prevents the addition of elements when set traversal, as in ArrayList}
View Code

③,addlast (e E)

 Public void AddLast (e e) {    linklast (e);}
View Code

Same as Add (e e), adding elements at the end of the list

④,public void Add (int index, E Element)

Inserts an element into the specified position

 Public voidAddintindex, E Element) {    //determine if the index is out of Bounds return index >= 0 && index <= size;Checkpositionindex (index); if(index = = size)//if the index value equals the linked list sizeLinklast (Element);//Insert the node directly into the tail of the linked list;    ElseLinkbefore (element, node (index));}//get the node according to the index, because it is a linked list, unlike an array, in memory is not a contiguous location store, can not be directly based on the index to the value, need to look down from the head or tail downNode<e> node (intindex) {    //size >> 1 means shift, which means dividing by 2 by 1 times    if(Index < (size >> 1)) {//if the index is smaller than half of the linked listnode<e> x = First;//sets X as the head node, which represents the start of a traversal from the node         for(inti = 0; I < index; i++)//because you just need to find the index, you can stop at indexx = X.next;//move backwards from the first node until you move to the previous node in index to find the node at index        returnx; } Else{//if the index is larger than half of the linked listNode<e> x = Last;//set X as the tail node, which means that the traversal starts from the last grid node         for(inti = size-1; i > Index; i--) x= X.prev;//move forward from the last node until you move to a node after index to find the node at index        returnx; }}voidLinkbefore (e E, node<e>succ) {    Finalnode<e> pred = Succ.prev;//gets the previous node of the index node    FinalNode<e> NewNode =NewNode<> (Pred, E, succ);//constructs the newly inserted node, the new node pred is set to the previous node of the original linked list index, and next is set to the node at index of the original linked listSucc.prev = NewNode;//The last few references to the node at the original index are set to the new node    if(Pred = =NULL)//if the previous node of the Insert node reference is emptyfirst = NewNode;//head node set to new node    ElsePred.next= NewNode;//next of the previous node of the original index is set to the new nodesize++; Modcount++;}
View Code

We found that linkedlist each time the element was added only changed the previous pointer reference and the next pointer reference of the element, and there was no expansion. In contrast to ArrayList, you need to expand, and when you insert an element in the middle, all subsequent elements move one bit, and the efficiency difference between the two inserts is significant

Find element

①,get (int index)

 Public E get (int  index) {    // to determine if the index is out of Bounds return index >= 0 && index <= size;     checkelementindex (index);     // Node (index) has been mentioned above to get the actual elements    of the nodes return node (index). Item;}
View Code

②,indexOf (Object o)

Returns the index of the first occurrence of the specified element in a linked list

 Public intindexOf (Object o) {intindex = 0; if(O = =NULL) {//the found element is null         for(node<e> x = first; X! =NULL; x = X.next) {//iterate from the beginning to the next node.            if(X.item = =NULL)                returnIndex//if found, returns indexindex++; }    } Else{//the found element is not null         for(node<e> x = first; X! =NULL; x =x.next) {if(O.equals (X.item))//compare with equals                returnIndex//if found, returns indexindex++; }    }    return-1;//The specified element is not found, 1 is returned}
View Code

modifying elements
 Public E set (int  index, e Element) {    Checkelementindex (index);    Node<E> x = node (index); // Gets the node    at the specified index E oldval = X.item; // gets the actual element of the node at the specified index    X.item = element; // replaces the node element of the specified position with the element    that needs to be modified return Oldval; // returns the element value of the original node at the index }
View Code

Delete Element

①, deleting by index location

 PublicE Remove (intindex)    {Checkelementindex (index); //Gets the node at the specified position first    returnUnlink (node (index));} E Unlink (Node<E>x) {FinalE element =X.item; FinalNode<e> next =X.next; FinalNode<e> prev =X.prev; if(prev = =NULL) {//if the previous node of the delete node reference is null, the node is deleted as the head nodeFirst = next;//set the head node to delete the next node of the node}Else{Prev.next= Next;//Next node of the previous node of the deleted node points to the next nodes of the delete nodeX.prev =NULL;//set the previous node reference of the delete node to null, otherwise the list will be messed up    }    if(Next = =NULL) {//if the next node of the delete node reference is null, the node is deleted as a trailing nodelast = prev;//set the trailing node to the previous node of the delete node}Else{//not a tail nodeNext.prev = prev;//The prev of the next node that deletes the node points to the previous node of the delete nodeX.next =NULL;//set the next node reference of the delete node to null} x.item=NULL;//set the actual element of the delete node to null for easy garbage collectionsize--; Modcount++; returnelement;}
View Code

In contrast to ArrayList, LinkedList's delete action does not need to "move" a lot of data, making it more efficient

Summarize

ArrayList and LinkedList have advantages and disadvantages in performance:

1. For ArrayList and LinkedList, the overhead of adding an element at the end of the list is fixed. For ArrayList, the main point is to add an entry in the internal array, which may occasionally result in an array expansion, whereas for LinkedList, this overhead is uniform and creates a new node object.
2. Inserting or deleting an element in the middle of the ArrayList means that the remaining elements in the list will be moved, while the overhead of inserting or deleting an element in the middle of the linkedlist is fixed, and only the upper and lower reference addresses of the adjacent nodes of the element are changed.
3. LinkedList does not support efficient random element access because it needs to traverse lookups from the first element or the last element; ArrayList can be directly indexed to the element corresponding to the position.
4. ArrayList space waste is mainly reflected in the end of the list to reserve a certain amount of space, and the space cost of LinkedList is reflected in its every element needs to consume considerable space, each element not only holds the actual content of the current element, There is also a reference to the previous node and the next node

Therefore, when we carry out the additions and deletions of the elements of the operation, the check operation with ArrayList, the best use of linkedlist when adding and deleting operations.

JDK1.8 source Code (II)--java.util.linkedlist

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.