Java-linkedlist Source Code Analysis

Source: Internet
Author: User
Tags addall null null

Java Improvement (22)---LinkedList

I. Overview

LinkedList and ArrayList as the implementation of the list interface, just ArrayList is the size of the list interface variable array implementation, LinkedList is the list interface chain list implementation. A list-based approach makes LinkedList better than ArrayList when inserting and deleting, while random access is less than ArrayList.

The LinkedList implements all optional list operations and allows all elements to include NULL.

In addition to implementing the list interface, the LinkedList class provides a uniform naming method for the get, remove, and insert elements at the beginning and end of the list. These operations allow the link list to be used as a stack, queue, or double-ended queue.

This class implements the Deque interface for Add, poll, and other stack and double-ended queue operations.

All actions are performed as required by the list of double links. Indexing in the list iterates through the list from the beginning or end (from one end near the specified index).

At the same time, this implementation is not synchronous as with ArrayList.

(This is excerpted from the JDK 6.0 API).

Ii. Source Code Analysis 2.1, definition

First we look at the definition of LinkedList:

 Public class Linkedlist<e>    extends abstractsequentiallist<e>    implements List<e> Deque<e>, Cloneable, java.io.Serializable

From this code we can clearly see LinkedList inherit abstractsequentiallist, implement list, Deque, cloneable, Serializable. Abstractsequentiallist provides a backbone implementation of the list interface, minimizing the effort required to implement this interface supported by "continuous access" data stores, such as linked lists, to reduce the complexity of implementing the list interface. Deque a linear collection that supports inserting and removing elements at both ends, defining the operation of a double-ended queue.

2.2. Properties

Two basic properties are provided in LinkedList size, header.

Private transient New Entry<e> (nullnull null); Private transient int size = 0;

where size represents the size of the LinkedList, the header represents the table header of the list, and entry is the node object.

 private  static  class         Entry<e> {E element;     //  element node  entry<e> next; //          Entry<e> previous; //  previous element   Entry (E element, Entry  <E> Next, Entry<e> previous) { this . Element = element;             this . Next = next;         this . Previous = previous; }    }

The above is the source code for the Entry object, entry is the inner class of LinkedList, which defines the stored elements. The element's previous element, the latter element, is a typical way of defining a doubly linked list.

2.3. Construction method

LinkedList has improved two construction methods: Linkedlis () and LinkedList (collection<? extends e> c).

/**      *  constructs an empty list.      */     Public LinkedList () {        = header.previous = header;    }         /**      *  constructs a list containing the elements in the specified collection, arranged in the order returned by their collection iterators.      */     Public extends E> c) {        this();        AddAll (c);    }

LinkedList () constructs an empty list. There is no element in it, just the first element of the header node and the last element point to itself.

LinkedList (collection<? extends e> c): Constructs a list that contains the elements in the specified Collection, arranged in the order that they are returned by their Collection iterator. The constructor first calls LinkedList (), constructs an empty list, and then calls the AddAll () method to add all the elements in the collection to the list. The following is the source code for AddAll ():

/*** Add all elements in the specified collection to the end of this list, in order to specify the order in which the collection iterators return the elements. */     Public BooleanAddAll (collection<?extendsE>c) {returnAddAll (size, c); }        /*** Inserts all the elements in the specified collection from the specified position at the beginning of this list. Where index indicates the index in which the first element in the specified collection is inserted*/     Public BooleanAddAll (intindex, COLLECTION&LT;?extendsE>c) {//throws a Indexoutofboundsexception exception if the inserted position is less than 0 or greater than the linked list length        if(Index < 0 | | index >size)Throw NewIndexoutofboundsexception ("index:" + index + ", Size:" +size); Object[] a=C.toarray (); intNumnew = A.length;//number of inserted elements//returns False if the inserted element is empty        if(Numnew = = 0)            return false; //modcount: Defined in Abstractlist, indicating the number of times the list has been modified from the structuremodcount++; //Gets the node at the insertion position, or the head node if the position is inserted at size, otherwise gets the node at the index positionentry<e> successor = (index = = size?)header:entry (index)); //The previous node of the insertion position, which needs to modify the next reference of the node during the insertion: point to the inserted node elementEntry<e> predecessor =successor.previous; //perform an Insert action         for(inti = 0; i < numnew; i++) {            //constructs a node E, where the Insert node action has been executed and the point reference of the neighboring node has been modified//Entry<e> E =NewEntry<e>((E) A[i], successor, predecessor); //points to the current element in the next element reference of the previous node in the insertion positionPredecessor.next =e; //modifies the previous node in the insertion position, which is done by moving the insertion position right one bit, ensuring that subsequent elements are inserted behind the element, ensuring the order of the elementspredecessor =e; } successor.previous=predecessor; //Modify Capacity SizeSize + =numnew; return true; }

In the AddAll () method, two methods are involved, one is entry (int index), which is a private method of LinkedList, primarily the node element used to find the index position.

/*** Returns the node element at the specified position (if present)*/    PrivateEntry<e> Entry (intindex) {        if(Index < 0 | | | Index >=size)Throw NewIndexoutofboundsexception ("index:" + index + ", Size:" +size); //head NodeEntry<e> E =header; //determine the direction of traversal        if(Index < (size >> 1)) {             for(inti = 0; I <= index; i++) e=E.next; } Else {             for(inti = size; i > Index; i--) e=e.previous; }        returne; }

From this method there are two traversal directions we can also see that LinkedList is a doubly linked list, which is also in the construction method why the header of the front and rear nodes are pointed to themselves.

If you have a little understanding of the data structure, the above-mentioned content should be a problem, we just need to be clear: LinkedList is a doubly linked list, the rest is solved.

Due to the limited space, the following will be used in linkedlist several common methods for source code analysis.

2.4, increase the method

Add (e E): Adds the specified element to the end of this list.

 Public Boolean Add (e e) {    Addbefore (e, header);         return true ;    }

The method calls the Addbefore method, and then returns true directly, for Addbefore (), which is a private method of LinkedList.

PrivateEntry<e> Addbefore (e E, entry<e>entry) {        //using the entry constructor to construct a new node newEntry,Entry<e> NewEntry =NewEntry<e>(E, entry, entry.previous); //Modify the reference of the front and back nodes of the newentry to ensure that the referential relationships of their linked lists are correctNewEntry.previous.next =NewEntry; NewEntry.next.previous=NewEntry; //capacity +1size++; //number of changes +1modcount++; returnNewEntry; }

In the Addbefore method nothing is done about it: Build a new node newentry, and then modify the references before and after it.

LinkedList also provides additional ways to add:

Add (int index, E Element): Inserts the specified element in the location specified in this list.

AddAll (collection<? extends e> c): Adds all the elements in the specified Collection to the end of this list, in order to specify the order in which the Collection iterator returns the elements.

AddAll (int index, COLLECTION<? extends e> c): Inserts all the elements in the specified Collection from the specified position to the list.

AddFirst (e E): Inserts the specified element at the beginning of this list.

AddLast (e E): Adds the specified element to the end of this list.

2.5. Removal method

Remove (Object o): Removes the first occurrence of the specified element (if present) from this list. The source code for this method is as follows:

 Public BooleanRemove (Object o) {if(o==NULL) {             for(entry<e> e = Header.next; E! = header; e =e.next) {if(e.element==NULL) {remove (e); return true; }            }        } Else {             for(entry<e> e = Header.next; E! = header; e =e.next) {if(O.equals (e.element)) {remove (e); return true; }            }        }        return false; }

The method first determines whether the removed element is null, then iterates through the list to find the element node, and finally calls remove (entry<e> e), and remove (entry<e> e) is a private method. is the base method for all the removal methods in LinkedList, as follows:

PrivateE Remove (entry<e>e) {if(E = =header)Throw Newnosuchelementexception (); //retain the removed element: to returnE result =e.element; //point the next node of the node to the node after the nodeE.previous.next =E.next; //Point the previous of the next node of the node to the node's front node//in these two steps, you can remove the node from the linked list: In the linked list, you cannot traverse to that node.E.next.previous =e.previous; //leave the node emptyE.next = E.previous =NULL; E.element=NULL; Size--; Modcount++; returnresult; }

Other removal methods:

Clear (): Removes all elements from this list.

Remove (): Gets and removes the header of this list (the first element).

Remove (int index): Removes the element at the specified position in this list.

Remove (objec o): Removes the first occurrence of the specified element (if present) from this list.

Removefirst (): Removes and returns the first element of this list.

Removefirstoccurrence (Object o): Removes the first occurrence of the specified element from this list (when traversing the list from head to tail).

Removelast (): Removes and returns the last element of this list.

Removelastoccurrence (Object o): Removes the last occurrence of the specified element from this list (when traversing the list from head to tail).

2.5. Search method

For the lookup method of the source code there is no good introduction, nothing more than iteration, compare, and then return the current value.

Get (int index): Returns the element at the specified position in this list.

GetFirst (): Returns the first element of this list.

GetLast (): Returns the last element of this list.

IndexOf (Object O): Returns the index of the specified element that first appears in this list, or 1 if the element is not included in this list.

LastIndexOf (Object O): Returns the index of the last occurrence of the specified element in this list, or 1 if the element is not included in this list.

Java-linkedlist Source Code Analysis

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.