LinkedList of the Java Collection class

Source: Internet
Author: User

I. Introduction of LinkedList

Since LinkedList is a dual-ended queue that implements Deque, LinkedList can be used as a queue and as a stack, using pop (), push (), Peek () when LinkedList as a stack. The way to note is that the LinkedList is the head of the list as the top of the stack, the tail of the list as the bottom of the stack

LinkedList is a doubly linked list, no initialization size, no expansion mechanism, is always in front of or behind the new is good

Features: Slow random access, fast insertion and deletion

Second, source code analysis

Because the LinkedList implements the list and the Deque two interfaces, so the LinkedList method is divided into two kinds, one is the method of the list interface, the second is the method of Deque interface.

1. Global variables

(1) The number of data in the current linked list

 transient int size = 0;

(2) Pointing to the list head

 transient Node<E> first;

(3) pointing to the tail of the list

 transient Node<E> last;
2. Constructor function

(1) method of constructing without parameters

 public LinkedList() {}

(2) Construction method with collection parameters

 public LinkedList(Collection<? extends E> c) {    this();    addAll(c);//}

description : When using the second construction method, the AddAll () method is called to add elements from the collection to the linked list

3. Methods

(1) linklast (e E)

 void linkLast(E e) {    final Node<E> l = last;//指向链表尾部    final Node<E> newNode = new Node<>(l, e, null);//以尾部为前驱节点创建一个新节点    last = newNode;//将链表尾部指向新节点    if (l == null)//如果链表为空,那么该节点既是头节点也是尾节点        first = newNode;    else//链表不为空,那么将该结点作为原链表尾部的后继节点        l.next = newNode;    size++;//增加尺寸    modCount++;}

description : The Linklast method is to add a double-ended node to the tail of a linked list, but pay attention to the processing of the head node when the list is empty
(2) node (INE index) (returns node based on index)

 Node<E> node(int index) {    // assert isElementIndex(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;    }}

(3) Linkbefore (e E, node< e > Succ)

 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++;}

(4) Linkfirst (e E)

 private void linkFirst(E e) {    final Node<E> f = first;    final Node<E> newNode = new Node<>(null, e, f);//新建节点,以头节点为后继节点    first = newNode;    //如果链表为空,last节点也指向该节点    if (f == null)        last = newNode;    //否则,将头节点的前驱指针指向新节点    else        f.prev = newNode;    size++;    modCount++;}

Description :

    1. Create a NewNode node, point the NewNode's successor pointer to SUCC, and the precursor pointer to pred
    2. Point the SUCC's precursor pointer to the NewNode
    3. Depending on whether pred is null, different operations are performed.
      • If pred is null, indicates that the node is inserted before the head node to reset the first head node
      • If pred is not NULL, then direct Pred's successor pointer to NewNode

(5) Unlink (node< E > 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;     }

(6) Unlinkfirst (Node 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;    }

(7) Unlinklast (node< E > L)

   private E unlinkLast(Node<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;}
(1) Add Operation for list interface

Add (e) for adding elements to the tail of the list

 public boolean add(E e) {    linkLast(e);    return true;    }

Add (int index,e E) for adding elements at the specified location

 public void add(int index, E element) {    checkPositionIndex(index);    if (index == size)        linkLast(element);    else        linkBefore(element, node(index));}

description : 1, check the range of index, otherwise throw exception 2, if the insertion position is the tail of the list, then call Lindlast Method 3, if the insertion position is the middle of the list, then call the Linkbefore method

AddAll has two methods, a method of a parameter that adds a collection element to the tail of the list, and a method of two arguments that specifies where to start the insertion.

 Inserts the collection at the end of the list, that is, the start index position is size public boolean addall (collection<? extends e> c) {return AddAll (size, c);    }//Inserts the collection from the specified position to the public boolean addall (int index, collection<? extends e> c) {//step 1: Check the index range    Checkpositionindex (index);    Step 2: Get the Set data object[] A = C.toarray ();    int numnew = A.length;    if (numnew = = 0) return false;    Step 3: Obtain the insertion position of the precursor node and the successor node node<e> pred, succ;        If the insertion position is trailing, the predecessor node is last, and the successor node is null if (index = = size) {SUCC = null;    Pred = Last;        }//Otherwise, call the node () method to get the successor node, and then get the precursor node else {succ = node (index);    pred = Succ.prev;        }//step 4: Traverse data to insert data into for (Object o:a) {@SuppressWarnings ("unchecked") e E = (e) o;        Create a new node node<e> newNode = new Node<> (pred, E, NULL);        If the insertion position is in the list header if (pred = = null) first = NewNode;        else Pred.next = NewNode;    pred = NewNode;    }//If the insertion position is at the tail, reset the last nodeif (succ = = null) {last = pred;        }//Otherwise, connect the inserted list with the previous linked list else {pred.next = SUCC;    Succ.prev = pred;    } size + = Numnew;    modcount++; return true;}

description : 1. Check Index Range
2. Get Collection data
3. Get the precursor and successor of the insertion position
4. Traverse the data to insert the data into the specified location

(2) Add operation of Deque interface

Push (e E)

    public void push(E e) {    addFirst(e);}

Description : The Push (e) method is used to add elements to the list header
AddFirst (e E)

 public void addFirst(E e) {    linkFirst(e);}

description : The AddFirst (e) method is used to add elements to the list header

AddLast (e E)

 public void addLast(E e) {    linkLast(e);}

description : The AddLast () method is used to add elements to the tail of the list, just as the Add method does, except that the return is different

Offer (e e)

 public boolean offer(E e) {    return add(e);}

Description : This method is used to add data to the end of the list, which internally calls the Add (E) method

Offerfirst (e E)

 public boolean offerFirst(E e) {    addFirst(e);    return true;}

Description : This method is used to insert data into the head of a linked table, unlike AddFirst, where the method returns a specific return value, while the AddFirst return value is void

Offerlast (e E)

 public boolean offerLast(E e) {    addLast(e);    return true;}

Description : The difference between offerlast () and AddLast () is the same as the difference between Offerfirst () and AddFirst ()

(3) Take data based on location

Get the Get (int index) method at any location

 public E get(int index) {    //检查边界    checkElementIndex(index);    return node(index).item;}

Description : The Get (int index) method returns data based on the specified index, and throws an exception if the index is out of bounds

Gets the head node data at position 0

There are many ways to get the data of the head node in LinkedList, the difference is that when the list is empty, whether to throw an exception or return null

where the GetFirst () and Element () methods will throw an exception when the list is empty:

 public E getFirst() {    final Node<E> f = first;    if (f == null)        throw new NoSuchElementException();    return f.item; } public E element() {    return getFirst();}

Peek () and Peekfirst () return NULL when the linked list is empty

Gets the tail node data at the location of Size-1

The GetLast () method throws an exception when the list is empty

 public E getLast() {    final Node<E> l = last;    if (l == null)        throw new NoSuchElementException();    return l.item;    }

The Peeklast () method returns NULL when the linked list is empty

  public E peekLast() {    final Node<E> l = last;    return (l == null) ? null : l.item; }
(4) Get an index based on the object (once matched, return to index immediately)

IndexOf (Object o)

 //返回第一个匹配的索引    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;     }     

LastIndexOf (Object o)

 //返回最后一个匹配的索引    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;     }
(5) Check whether the linked list contains objects

Contains (Object o)

 public boolean contains(Object o) {    return indexOf(o) != -1;    }

Description : The contains (object O) method checks to see if the object o exists in the linked list, this method calls the IndexOf method, as long as the return result is not-1, indicating that the object exists in the linked list

(6) Delete the specified object

Remove (Object o)

 public boolean remove(Object o) {    //如果删除对象为null    if (o == null) {        //从前向后遍历        for (Node<E> x = first; x != null; x = x.next) {            //一旦匹配,调用unlink()方法和返回true            if (x.item == null) {                unlink(x);                return true;            }        }    } else {        //从前向后遍历        for (Node<E> x = first; x != null; x = x.next) {            //一旦匹配,调用unlink()方法和返回true            if (o.equals(x.item)) {                unlink(x);                return true;            }        }    }    return false;    }

Note : When you delete a specified object, you only need to call remove (object o), but the method deletes only one matching object at a time, and returns true if the matching object is deleted, otherwise false.

(7) Delete objects by location

Delete an object at any specified location

 public E remove(int index) {    //检查index范围    checkElementIndex(index);    //将节点删除    return unlink(node(index));}

Delete the head node object
Remove (), Removefirst (), pop () will be thrown when the list is empty nosuchelementexception

 public E remove() {    return removeFirst();}public E pop() {    return removeFirst();}public E removeFirst() {    final Node<E> f = first;    if (f == null)        throw new NoSuchElementException();    return unlinkFirst(f);}

Poll (), Pollfirst () returns null if the list is empty

 public E poll() {    final Node<E> f = first;    return (f == null) ? null : unlinkFirst(f);}public E pollFirst() {    final Node<E> f = first;    return (f == null) ? null : unlinkFirst(f);}
(8) Delete the elements of the tail node

Removelast () will throw nosuchelementexception when the list is empty

 public E removeLast() {    final Node<E> l = last;    if (l == null)        throw new NoSuchElementException();    return unlinkLast(l);}

The Polllast () method returns NULL when the list is empty

 public E pollLast() {    final Node<E> l = last;    return (l == null) ? null : unlinkLast(l);}
(9) Iterator operation

Iterator (), Listiterator (), listiterator (int index)

 public Iterator<E> iterator() {    return listIterator();}    public ListIterator<E> listIterator() {    return listIterator(0);}   public ListIterator<E> listIterator(int index) {    checkPositionIndex(index);    return new ListItr(index);}
4. Inner class (1) node< E >
 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;    }}

description : From the definition of node, we can see that the linked list is a double-ended linked list structure

(2) Listitr
   Private class Listitr implements listiterator<e> {private node<e> lastreturned;    Private node<e> Next;    private int nextindex; private int expectedmodcount = modcount;//Save current modcount, ensure fail-fast mechanism listitr (int index) {//Assert Ispositionin        Dex (index); Next = (index = = size)?    Null:node (index);//Gets the current index pointing to the next node Nextindex = index;    } public boolean Hasnext () {return nextindex < size;        }//Get Next node public E next () {checkforcomodification ();        if (!hasnext ()) throw new Nosuchelementexception ();        lastreturned = Next;        Next = Next.next;        nextindex++;    return lastreturned.item;    } public boolean hasprevious () {return nextindex > 0;        }//Gets the previous node, moving the next node forward to public E previous () {checkforcomodification ();        if (!hasprevious ()) throw new Nosuchelementexception (); lastreturned = Next = (next = null)? Last:next.prev;        nextindex--;    return lastreturned.item;    } public int Nextindex () {return nextindex;    } public int Previousindex () {return nextIndex-1;        } public void Remove () {checkforcomodification ();        if (lastreturned = = null) throw new IllegalStateException ();        node<e> lastnext = Lastreturned.next;        Unlink (lastreturned);        if (next = = lastreturned) next = Lastnext;        else nextindex--;        lastreturned = null;    expectedmodcount++;        } public void set (E e) {if (lastreturned = = null) throw new IllegalStateException ();        Checkforcomodification ();    Lastreturned.item = e;        } public void Add (e e) {checkforcomodification ();        lastreturned = null;        if (next = null) Linklast (e);        else Linkbefore (e, next);        nextindex++;    expectedmodcount++; } public void Foreachremaining (Consumer<?        Super e> Action) {Objects.requirenonnull (action);            while (Modcount = = Expectedmodcount && Nextindex < size) {action.accept (Next.item);            lastreturned = Next;            Next = Next.next;        nextindex++;    } checkforcomodification (); } final void Checkforcomodification () {if (Modcount! = expectedmodcount) throw new concurrentmodific    Ationexception (); }}
Third, deque interface description

Deque is the sub-interface of the queue, we know that queue is a form of queues, and Deque is a two-way queue that supports retrieving and inserting and deleting elements from two endpoint orientations

Method

When Deque is used as a queue (FIFO), the added element is added to the tail of the team, and the deletion is the head element, where the method is:

Queue Method Deque Method
Add (E) AddLast (e)
Offer (e) Offerlast (e)
Remove () Removefirst ()
Poll () Pollfirst ()
Element () GetFirst ()
Peek () Peekfirst ()

Deque can also be used as a stack (LIFO). At this point in the stack, the stack elements are in the double-ended queue of the head, wherein the method is:

Stack Method Deque Method
Push (e) AddFirst (e)
OOP () Removefirst ()
Peek () Peekfirst ()

The method is detailed:
void AddFirst (e e);

The object E is inserted into the head of the double-ended queue, and the IllegalStateException exception is thrown when the tolerance is insufficient;

void AddLast (e e);

The object E is inserted into the tail of the double end queue, and the IllegalStateException exception is thrown when the tolerance is insufficient;

Boolean Offerfirst (e e);

Inserting object e into the double-ended queue header

Boolean offerlast (e e);

Inserts the object e into the tail of the double-ended queue;

E Removefirst ();

Gets and removes the first element of the queue, the queue is empty, throws a Nosuchelementexception exception;

E Removelast ();

Gets and removes the last element of the queue, which is empty and throws a Nosuchelementexception exception;

E Pollfirst ();

Gets and removes the first element of the queue, the queue is empty, and Null is returned;

E Polllast ();

Gets and removes the last element of the queue, the queue is empty, and Null is returned;

E GetFirst ();

Gets the first element of the queue, but does not remove, the queue is empty and throws a Nosuchelementexception exception;

E GetLast ();

Gets the last element of the queue, but does not remove, the queue is empty and throws a Nosuchelementexception exception;

E Peekfirst ();

Gets the first element of the queue, the queue is empty, and Null is returned;

E Peeklast ();

Gets the last element of the queue, the queue is empty, and Null is returned;

Boolean removefirstoccurrence (Object o);

Remove the first element satisfying (O==null e==null:o.equals (e))

Boolean removelastoccurrence (Object o);

Remove the last element that satisfies (O==null e==null:o.equals (e))

void push (e e);

Inserts the object e into the double-ended queue header;

E pop ();

Remove and return the first element of a double-ended queue

Iterator descendingiterator ();

A double-ended queue tail to the head of an iterator;

Implementation scenarios

The implementation classes of deque are mainly divided into two kinds of scenarios

General Scenario:

    • LinkedList variable-size linked list double-ended queue, allowing elements to be null
    • Arraydeque variable-size array double-ended queue, null not allowed

concurrency scenarios

    • Linkedblockingdeque if the queue is empty, the get operation will block, knowing that an element is added

LinkedList of the Java Collection class

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.