Linledlist Source Code Analysis

Source: Internet
Author: User
Tags concurrentmodificationexception

LinkedList Source Code Analysis

        • LinkedList Source Code Analysis
          • Brief introduction
          • Structure
          • Internal class explanation
          • Explanation of Property Expectedmodcount property
          • Main methods Explained

--Introduction
    • LinkedList the bottom layer is implemented using a two-wire linked list, adding arrays to this collection or removing them from the collection is all about adding nodes and deletions and nodes to the doubly linked list.
    • The Modcount attribute defined in the class Abstractsequentiallist implemented by LinkedList makes it possible for a collection that inherits from it to not asynchronously perform an incremental delete of the collection, and so on, that is, the operation is thread insecure.
--Structure

LinkedList inherits from Abstractsequentiallist, realizes the list, Deque, cloneable, java.io.Serializable interface.
The following are the inner classes in LinkedList and the important properties:
-Inner class
-Private class Listitr implements Listiterator
-Private Static Class Entry
-Private class Descendingiterator implements Iterator
-Main properties
-Private Transient Entry header = new Entry (null, NULL, NULL);
-private transient int size = 0;
-Construction method
-Public LinkedList ()
-Public LinkedList (Collection

--Internal class explanation
    • static inner class entry
      As mentioned above, LinkedList is implemented using a doubly linked list, so this class defines the data structure of the doubly linked list. If you don't know the two-way list, look at the data structure.
privatestaticclass Entry<E> {    E element;    Entry<E> next;    Entry<E> previous;}//双向链表,所以定义了前后指针
    • Inner class Listitr
      Looking at the description of the introduction, we will find that this class implements the Listiterator interface, so the LinkedList collection can iterate over the elements, and he finds the next element in the list by means of a replication and Hasnext () in the mouth until the list is empty.

      • Property
        Private Entry lastreturned = header;//Record last traversal node
        Private Entry next;//used to traverse elements
        private int nextindex;//records the subscript of the current element
        private int expectedmodcount = Modcount; (A-Last talk)

      • Construction method
        LISTITR (int index)
        The construction method of this class is important. Its main function is to find the index subscript element so that it can traverse all before or after this element.
        Implementation principle: If the index value passed in is less than 0 or larger than the size of LinkedList, then we will see the unusual indexoutofboundsexception that often occurs. If index is less than half of the array size (size), attach the head pointer to next and then traverse from No. 0 of the array to index to find the element that is labeled Index. If the value of index is greater than half of the value of the array, then the tail pointer is paid to next, and then the back-and-forth collection is known to find the element corresponding to index, so that each iteration does not exceed half the size of the array, greatly improving efficiency.
        Let's see what he does:

Listitr (int Index) {if(Index<0||Index> Size) throw new Indexoutofboundsexception ("Index:"+Index+", Size:"+size);if(Index< (size >>1)) {Next= header.Next; for(nextindex=0; nextindex<Index; nextindex++)Next=Next.Next; }Else{Next= header; for(Nextindex=size; nextindex>Index; nextindex--)Next=Next. previous; }    }

The

can see how it computes half of the array: (Size >> 1) is to move the size right one bit, on the computer, the number is represented as a binary, the right one means dividing the size by 2, and the opposite moving left one represents multiplying by 2.
-How to implement Listiterator
because this inner class implements the Listiterator interface, we now mainly talk about three methods:
**1.**public void Add (e e)
The purpose of this method is to add an element to a collection. The added method uses the tail interpolation method, so lastreturned is appended to the header (this means that LinkedList uses a doubly linked list to place the head node position at the end of the list), and then calls the method Addbefore inserts the element e into the tail of the list, adding 1 to the position of the current element.

public   void  add  (e e) {checkforcomodification ();  lastreturned = header;        Addbefore (E, next);        nextindex++; expectedmodcount++;    //d-then together to speak } Look at the code for Addbefore: private  entry<e> addBefore  (e E, entry<e> Entry) {entry<e> newEntry = new  entry<e>        (E, entry, entry.previous);        NewEntry.previous.next = NewEntry;        newEntry.next.previous = NewEntry;        size++; modcount++;        //c-the last issue of the     return  newEntry; }

**2.**private e Remove (Entry e)
The method of deleting an element is simple, that is, the deletion of the two-way list, but it is important to note the order, the order of the deleted four lines of code can not be changed. After deletion, subtract the size of the collection by one.

Private E Remove (entry<e> e) {if (E = = header) throw new Nosuchelementexception ();E result = E. Element;E. Previous. Next= E. Next;E. Next. Previous= E. Previous;E. Next= E. Previous= NULL;E. Element= NULL;size--;modcount++;return result;}

**3.**public E Previous ()
This method is primarily able to find the previous element in reverse order. If the attribute Nextindex that represents the current element subscript is equal to 0, indicating that the list is empty, the exception is thrown nosuchelementexception; Marks the attribute lastreturned of the previous element as the element to look for (lastreturned = next = next.previous;) Of course, the following table of the current element is also reduced because it is a reverse-order traversal.

    publicprevious() {        if0)        thrownew NoSuchElementException();        lastReturned = next = next.previous;        nextIndex--;        checkForComodification();        return lastReturned.element;    }

The same, checkforcomodification (); and at the end of the story.
- internal class Descendingiterator
This inner class is the implementation of the set of the subtraction traversal, the implementation of the Interator interface. In the same way, when he traverses, the previous element can be previous by using the method of an internal class LISTITR replication.

 private   class  descendingiterator  implements  iterator  { final  listitr itr = new  listitr (Size ()        ); public  boolean  hasnext         () {return  itr.hasprevious (); } public  E next  () {return  itr.previous (); } public  void  remove         () {itr.remove (); }    }
--Explanation of attribute Expectedmodcount property
    • The Expectedmodcount=modcount at a
      Modcount is a property of LinkedList inherited from his parent class. This is a very simple assignment statement, see Abstractlist Source code we can know that the type of property Modcount is pretected type, he is used to inherit the subclass.
    • Checkforcomodification () at B;
      In the Add method in the inner class Listitr, this method is called first, so let's see what this method does.
privatevoidcheckForComodification() {        if (this.modCount != l.modCount)            thrownew ConcurrentModificationException();    }

I can see that this class is to check whether the Modcount in the subclass is consistent with the Modcount in his parent class, and if the inconsistency throws an exception concurrentmodificationexception; he's here. We'll analyze it when we finish the C and D.
-Explanation of modcount++ at C
This code appears in the Addbefore of the Add method call, and we can see that whenever an element is added to the collection, calling the Addbefore method will now add a modcount to the parent class abstractlist. That's what we're going to say next.
-Explanation of ecpectedmodcount++ at D
This code also appears in the Add method, I can see in Addbefore the parent class of the Modcount plus one later on the subclass LinkedList Expectedmodcount value plus one.

Now let's talk about the benefits of doing this.
When the synchronization operation or single-threaded, the operation of the collection is not a problem, if the multi-threaded concurrency? If a thread in an operation collection keeps deleting elements, and a collection keeps adding elements, what's the point of this set? To keep this from happening, the JDK designer requires that it not be used asynchronously and throws an exception if you have to use it asynchronously. How does the JDK prevent users from being able to use it asynchronously? It's the ABCD above. When the user adds an element, first check that the parent class's modcount is the same as the expectedmodcount of the subclass (call the Checkforcomodification () method), if it is not the same, it means that there are multiple threads in the Operation collection, then throw an exception, If the same, the parent class Modcount plus one, and then the subclass of the Expectedmodcount plus one, which also has the code executed. Because of this, if the asynchronous artificial, it is possible to cause the program does not follow the expected sequence of execution, then it is likely to cause Fred Modcount and subclasses Expectedmodcount inconsistent, so that when added will throw an exception.

--Main methods explained

In fact, in the LinkedList, as long as the data structure and internal classes, then the next linkedlist in the operation of the elements are around these internal classes to achieve.
Now let's take a look at the methods in LinkedList
-Public boolean Add (E E)
This method adds an element to the collection. We can see that his implementation code is invoking the method in the inner class to implement his function.

    publicbooleanadd(E e) {        addBefore(e, header);        returntrue;    }如果前面的看懂了,那应该没有任何难度了。-  publicremove(int index)此方法从集合中删除指定的元素。

Public E Remove (int index) {
Return Remove (Entry (index));
}

也是调用前面内部类中的方法。这里就不详细讲解了,又不理解的看看内部类中的讲解。####------实现的接口的讲解- **List接口**有序的 collection(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。与 set 不同,列表通常允许重复的元素。更正式地说,列表通常允许满足 e1.equals(e2) 的元素对 e1 和 e2,并且如果列表本身允许 null 元素的话,通常它们允许多个 null 元素。(来自JDK)- **Deque接口**一个线性 collection,支持在两端插入和移除元素。相当于一个队列,的确LinkedList中有对队列操作的方法,即,你可以将一个LinkedList当成一个队列来使用。队列的方法主要有以下:**1.**public void push(E e)和队列相同,如果需要插入一个元素的话就在链表的尾部插入一个元素,同样的调用的时候仍然是使用上面内部类中的操作。
public void addFirst(E e) {    addBefore(e, header.next);//上面讲过}
我们浏览内部类的讲解可以看到addBefore是在链表的尾部插入元素,正好符合队列的要求。**2.publicpop()如果需要删除一个元素,那么就要在链表的头部删除。
public E pop() {    return removeFirst();}//我们来看一下removeFist的实现 public E removeFirst() {    return remove(header.next);}

"'
We can see that the Remove method in the inner class is called again, but we notice that the parameter in remove is the header. Next, as mentioned above, LinkedList in the two-way list is the head pointer to the tail, so Header.next is the head, the head node passed in to delete the head. Realized the idea of the queue.

    • Cloneable interface

This class implements the Cloneable interface to indicate that the Object.clone () method can legitimately replicate the class instance by field.
Invoking the Clone method of Object on an instance that does not implement the Cloneable interface causes the clonenotsupportedexception exception to be thrown.
By convention, a class that implements this interface should use a public method to rewrite the Object.clone (which is protected).

The clone of the LinkedList collection is a shallow clone, in general clone is a recursive first clone of the object itself, and then the properties of the object, the method and so on. However, in LinkedList, cloning only clones the LinkedList itself, and its elements are not recursive cloning, so that linkedlist is shallow cloning.

    • java.io.Serializable
      Using the Serializable interface allows this collection to be serialized, when the memory is not enough, the object can be written as a binary file into the hard disk, and then read out from the hard disk when needed, and then recover. This will save memory. A collection is a larger object, and if it has been loaded into a virtual machine but is not used frequently, because he is also a strong reference, the garbage collector cannot recycle it, and if he survives too long and the garbage collection period has shifted to the old age, long-term survival can cause GC,GC to be a time-consuming process, We don't want to be in this situation, so serialize it and then use IO to read it from the hard disk when needed.

more Java source code parsing:
Https://github.com/ccqy66/JDK-s-source-parser

Linledlist 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.