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 <e >     * *    private static class Node<e> {        E item;        Node<e> Next;        Node<e> prev;        Constructor method parameter order: predecessor  node Value following node        (node<e> prev, E element, node<e> next) {            This.item = element;            This.next = Next;            This.prev = prev;        }    }

public class Linkedlist<e> extends abstractsequentiallist<e> implements List<e>, Deque<e>,     Cloneable, java.io.serializable{//the number of elements transient int size = 0;    Point to the first node transient node<e>;    Point to the last node transient node<e>; 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<? extends e> c) {this ();    AddAll (c);        }//Insert E in front of the first position of the list, note that it is possible to modify last and primary private void Linkfirst (E e) {final node<e> f = firstly;        Final node<e> 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<e> L = final; Final node<e> 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<e> succ) {//assert succ! = null;        Final node<e> pred = Succ.prev;        Final node<e> 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<e> f) {//assert F = = primary && 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; }//Remove the last element of the list private E unlinklast (node&Lt        E> l) {//assert L = = Last && L! = null;        Final E element = L.item;        Final node<e> 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<e> x) {//assert x! = null;        Final E element = X.item;        Final node<e> next = X.next;        Final node<e> 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<e> 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<e> L = last;        if (L = = null) throw new Nosuchelementexception ();    return l.item;        }//removal of the first element public E Removefirst () {final node<e> f = primary;        if (f = = null) throw new Nosuchelementexception ();    Return Unlinkfirst (f);        }//Remove last element public E Removelast () {final node<e> L = final;        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<e> x = first; X! = null; x = X.next) {                    if (X.item = = null) {unlink (x);                return true; }}} else {for (node<e> x = first; X! = null; x = X.next) {if (O.equa                    LS (x.item)) {unlink (x);                return true;    }}} return false; }//From the end of LinkedList, add the collection C to the LinkedList public boolean addall (collection<? extends e> c) {return Addal    L (size, c);        }//Starting with index LinkedList, add elements from collection C to LinkedList public boolean addall (int index, COLLECTION&LT;? extends e> c) {        Checkpositionindex (index);        Object[] A = C.toarray ();        int numnew = A.length;        if (numnew = = 0)//Set C is empty, return false to false;    Node<e> pred, succ;//the previous node of the insertion position and the node at 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<e> NewNode = new Node<> (pred, E, NULL);            if (pred = = null) First = newnode;//always note 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<e> x = first; X! = null;)            {node<e> 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<e> x = node (index);        E oldval = X.item;        X.item = element;    return oldval;        }//-----Add a node with an element value of elements before index----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 Indexoutofboundsexception (o    Utofboundsmsg (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<e> nodes (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 lookup efficiency 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; }}//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<e> x = first; x ! = NULL;                x = X.next) {if (X.item = = null) return index;            index++;                    }} else {for (node<e> x = first; X! = null; x = X.next) {if (O.equals (X.item))                return index;            index++;    }} return-1; }//From the back of the search, the return value of the node position o, if there is no return 1, you can find the null location//Look for the first occurrence of the public int lastIndexOf (Object o) {int index = size        ;                if (o = = null) {for (node<e> x = last; x = null; x = X.prev) {index--;            if (X.item = = null) return index;                }} else {for (node<e> 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<e> 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<e> f = first; return (f = = null)?    Null:unlinkfirst (f);    } public E Remove () {return Removefirst ();    }//queue, add to footer public Boolean offer (e) {return add (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<e> f = first; return (f = = null)?     Null:f.item;        Public E Peeklast () {final node<e> L = last; return (L = = null)?    Null:l.item;        } public E Pollfirst () {final node<e> f = first; return (f = = null)?    Null:unlinkfirst (f);    } public E Polllast () {    Final node<e> 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<e> x = last; x = null; x = X.prev) {if (X.item = = null) {UN                    Link (x);                return true; }}} else {for (node<e> x = last; X! = null; x = X.prev) {if (o.equal                    S (x.item)) {unlink (x);                return true;    }}} return false; }//Return index to the end of all nodes corresponding to the Listiterator object public listiterator<e> listiterator (int index) {Checkpositioninde        X (index); return new Listitr (index);    }//list iterator Private class Listitr implements listiterator<e> {private node<e> Lastreturn ed;//last node returned private node<e> next;//next node private int nextindex;//next node index//expected change count, used to implement FAIL-F        AST mechanism private int expectedmodcount = Modcount;            LISTITR (int index) {//Assert Ispositionindex (index); Next = (index = = size)?            Null:node (index);        Nextindex = index; }
Public Object Clone () {linkedlist<e> 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<e> x = first; X! = null; x = x.next) Clone.add (x.i        TEM);    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

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.