Analysis of LinkedList source code of Java class set framework

Source: Internet
Author: User
Tags addall throw exception

LinkedList

LinkedList is based on a two-way cyclic chain list implementation. It can also be manipulated as a stack, a queue, or a double-ended queue. Non-thread safe. The following directly paste ArrayList Java implementation (only part of the code), source Jdk1.8.0_25/src.zip.

    /**     * * * * * * * * * * * The data structure *********     * contains: Node value item     *     precursor  pre     *     successor next         * @param      */    private Static class Node {        E item;        Node Next;        Node prev;        Constructor method Parameter order: the predecessor  node value follows node        (node prev, E Element, node next) {            This.item = element;            This.next = Next;            This.prev = prev;        }    }

public class LinkedList extends Abstractsequentiallist implements List, Deque, cloneable, java.io.serializable{//element number T     ransient int size = 0;    Point to transient node first    Point to the last node transient. Construct a method to construct an empty list public LinkedList () {}//constructor 2--constructs a list that contains the elements in the specified collection, in the order in which the collection iterators are returned, public linkedlis        T (Collection c) {this ();    AddAll (c);        }//Insert E in front of the first position of the list, note that the last and primary private void Linkfirst (E e) {final Node F = firstly may be modified;        Final Node NewNode = new node<> (null, E, F),//node (precursor, element, successor) First = NewNode;        if (f = = null) last = newnode;//before insertion is NULL then the previous is itself else F.prev = newnode;//if not empty then the head node precursor points to NewNode        size++;    modcount++;        }//Insert E into the last element of the list after void Linklast (E e) {final Node L = previous;        Final Node NewNode = new Node<> (l, E, null);        last = NewNode;        if (L = = null) first = NewNode; Else L.Next = NewNode;        size++;    modcount++;        }//node succ inserted before node void Linkbefore (e E, node succ) {//assert succ! = null;        Final Node pred = Succ.prev;        Final Node NewNode = new Node<> (pred, E, succ);        Succ.prev = NewNode;        if (pred = = null) first = NewNode;        else Pred.next = NewNode;        size++;    modcount++;        }//Remove the first element of the list private E Unlinkfirst (Node f) {//assert F = = primary && f! = null;        Final E element = F.item;        Final Node 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;        }//Remove the last element of the list private E unlinklast (Node l) {//assert L = = Final && L! = null;        Final E element = L.item;        Final Node 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 node x E Unlink (node x) {//assert x! = null;        Final E element = X.item;        Final Node next = X.next;        Final Node 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;        }//Gets the first element, if empty, throws an exception public E GetFirst () {final Node f = primary;        if (f = = null) throw new Nosuchelementexception ();    return f.item;        }//Gets the first element, if empty, throws an exception public E GetLast () {final Node L = last; if (L = = null) throw new NosuchelemEntexception ();    return l.item;        }//removal of the first element public E Removefirst () {final Node f = primary;        if (f = = null) throw new Nosuchelementexception ();    Return Unlinkfirst (f);        }//Remove the last element public E Removelast () {final Node L = previous;        if (L = = null) throw new Nosuchelementexception ();    Return Unlinklast (L);    }//Add element E as the first element of the list public void AddFirst (e e) {Linkfirst (e);    } public void AddLast (e e) {linklast (e);    } public boolean contains (Object o) {return indexOf (o)! =-1;    } public int size () {return size;    Public boolean Add (e) {linklast (e);//Add to last face return true; }//can remove the null element, starting from the linked list to find the specified element o public boolean remove (Object o) {if (o = = null) {for (Node x = f) Irst X! = NULL;                    x = X.next) {if (X.item = = null) {unlink (x);                return true;       }     }} else {for (Node x = first; X! = null; x = X.next) {if (O.equals (X.item)) {                    unlink (x);                return true;    }}} return false;    }//Starting at the end of LinkedList, add the collection C to the LinkedList public boolean addall (Collection c) {return AddAll (size, c); }//Starting with index LinkedList, add elements from collection C to LinkedList public boolean addall (int index, Collection c) {checkposition        Index (index);        Object[] A = C.toarray ();        int numnew = A.length;        if (numnew = = 0)//Set C is empty, return false to false;            Node pred, succ;//the previous node of the insertion position and the insertion position if (index = = size) {SUCC = null;        Pred = Last;            } else {SUCC = node (index);        pred = Succ.prev;            } for (Object o:a) {@SuppressWarnings ("unchecked") e E = (e) o;            Node NewNode = new Node<> (pred, E, null); if (pred = = null)                First = newnode;//always notice to modify first and last else Pred.next = NewNode;        pred = NewNode;        } if (succ = = null) {last = pred;            } else {pred.next = SUCC;        Succ.prev = pred;        } size + = numnew;//After adding a list of modcount++;    return true; }//Empty the doubly linked list public void clear () {for (Node x = first; X! = null;)            {Node next = X.next;            X.item = null;            X.next = null;            X.prev = null;        x = Next;        } first = last = null;        size = 0;    modcount++;        }//positional access Operations//Gets the specified position element public E get (int index) {checkelementindex (index);    Return node (index). Item;        }//sets the value of the specified position element and returns the original value public E set (int index, E element) {Checkelementindex (index);        Node x = node (index);        E oldval = X.item;        X.item = element;    return oldval; }//-----in INdex the node with the element value before it----public void Add (int index, E element) {Checkpositionindex (index);        if (index = = size) linklast (element);    else Linkbefore (element, node (index));        }//delete the specified location node public E Remove (int index) {checkelementindex (index);    Return unlink (node (index));    } private Boolean Iselementindex (int index) {return index >= 0 && index < size;    } private Boolean Ispositionindex (int index) {return index >= 0 && index <= size;    } private String outofboundsmsg (int index) {return "index:" +index+ ", Size:" +size; } private void Checkelementindex (int index) {if (!iselementindex (index)) throw new Indexoutofboundse    Xception (outofboundsmsg (index)); } private void Checkpositionindex (int index) {if (!ispositionindex (index)) throw new Indexoutofbound    Sexception (outofboundsmsg (index)); }//Previous version is entry, gets the node at the specified location   node node (int index) {//Assert Iselementindex (index);            To find a location that is less than half the list of two-way lists, look back from the previous, or look backward, and improve the search efficiency if (Index < (size >> 1)) {Node x = first;            for (int i = 0; i < index; i++) x = X.next;        return x;            } else {Node x = last;            for (int i = size-1; i > Index; i--) x = X.prev;        return x; }}//Search Operations//search for the position of the node with the value O, and if there is no return-1, you can find the null position//Look for the first occurrence of the public int indexOf (Object o)        {int index = 0;                    if (o = = null) {for (Node x = first; X! = null; x = X.next) {if (X.item = = null)                return index;            index++;                    }} else {for (Node x = first; X! = null; x = X.next) {if (O.equals (X.item))                return index;            index++;    }} return-1; }//From Back to back, return the node position with the value O, if there is no return-1, you can find the null location//Find the first occurrence of the public int lastIndexOf (Object o) {int index = size;                if (o = = null) {for (Node x = last; X! = null; x = X.prev) {index--;            if (X.item = = null) return index;                }} else {for (Node x = last; X! = null; x = X.prev) {index--;            if (O.equals (X.item)) return index;    }} return-1;        }/******* the operation used as a queue operations.************///returns the first node element, or null if NULL, gets but does not remove (does not exit the team) public E Peek () {        Final Node f = first; return (f = = null)?    Null:f.item;    }//returns the first node element, if an empty throw exception, equivalent to the team public E element () {return GetFirst ();        }//Out team, get and remove the header public E poll () {final Node f = first; return (f = = null)?    Null:unlinkfirst (f);    } public E Remove () {return Removefirst (); }//queue, add to footer public Boolean offer (E-e) {returnAdd (e);        }/**** Deque operations****/public boolean offerfirst (E e) {AddFirst (e);    return true;        } public boolean offerlast (E e) {addlast (e);    return true;        Public E Peekfirst () {final Node f = first; return (f = = null)?     Null:f.item;        Public E Peeklast () {final Node L = last; return (L = = null)?    Null:l.item;        Public E Pollfirst () {final Node f = first; return (f = = null)?    Null:unlinkfirst (f);        Public E Polllast () {final Node L = last; return (L = = null)?    Null:unlinklast (l);    public void push (E e) {AddFirst (e);    } public E Pop () {return Removefirst ();    public boolean removefirstoccurrence (Object o) {return remove (o);            }//Removes the last occurrence of the specified node, which is removed from the first node that is searched forward, and can be null public boolean removelastoccurrence (Object o) {if (o = = null) {  for (Node x = last; X! = null; x = X.prev) {              if (X.item = = null) {unlink (x);                return true; }}}} else {for (Node x = last; X! = null; x = X.prev) {if (O.equals (X.item)                    ) {unlink (x);                return true;    }}} return false;         }//Return index to the end of all nodes corresponding to the Listiterator object public listiterator listiterator (int index) {checkpositionindex (index);    return new Listitr (index); }//list iterator Private class Listitr implements Listiterator {private node lastreturned;//last returned node p Rivate node next;//next node private int nextindex;//next node index//expected change count, used to implement FAIL-FAST mechanism private int expect        Edmodcount = Modcount;            LISTITR (int index) {//Assert Ispositionindex (index); Next = (index = = size)?            Null:node (index);        Nextindex = index; }
Public Object Clone () {LinkedList clone = Superclone ();        Put clone into ' virgin ' state clone.first = Clone.last = null;        clone.size = 0;        Clone.modcount = 0;        Initialize clone with our elements for (Node x = first; X! = null; x = x.next) Clone.add (X.item);    return clone; }


constructor function:

There are 2 ways to construct LinkedList, one is to construct an empty list (head node null), and the other is to create an empty list, and then call AddAll (c) to initialize the elements in C.

Description

LinkedList is based on a two-way circular link list, there is no capacity shortage and expansion, but the efficiency of insertion and deletion is high. When inserting a node, create a new node object, find the location of the insertion node, change the precursor and successor. When a node is deleted, the predecessor of the successor and successor nodes of the predecessor node of the deleted nodes is changed, and the elements are not required to be moved.

LinkedList the allowable element is null, and when an element is found and deleted, both null and non-null are distinguished

LinkedList implements the stack and queue operations, such as push () pop () and other methods, in order to distinguish between different operations, many method names are not the same, but the function is the same.

Analysis of LinkedList source code of Java class set framework

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.