Chapter 3 parse the source code of listing, and parse the source code of Listing

Source: Internet
Author: User

Chapter 3 parse the source code of listing, and parse the source code of Listing

I. Eight points to be mastered for the listing list

  • Create a struct list: the constructor.
  • Add an object to the consumer list: add (E) Method
  • Obtain a single object in the listing list: get (int index) Method
  • Modify the data set (int index, E element) of the node with the specified index in the sorted list)
  • Delete objects in the listing list: remove (E), remove (int index)
  • Traverse objects in the consumer list: iterator. In practice, the enhanced for loop is more commonly used for traversal.
  • Determine whether the object exists in the inventory list: contain (E)
  • Sorting of objects in the SORT list: mainly depends on the Sorting Algorithm adopted (later)

Ii. Source Code Analysis

2.1,Shortlist.

Implementation Method:

List<String> strList0 = new LinkedList<String>();

Source code: before reading the source code, you must first know what a circular two-way linked list is. For more information, seeIntroduction to algorithms (second edition) P207

Private transient Entry <E> header = new Entry <E> (null, null, null); // The bottom layer is a two-way linked list, at this time, initialize an empty header node private transient int size = 0; // The number of elements stored in the linked list/*** create a circular bidirectional linked list */public writable list () {header. next = header. previous = header; // form a circular two-way linked list}

Entry is an internal class of the shortlist:

/*** Linked list node */private static class Entry <E> {E element; // The data Entry stored by the linked list node <E> next; // Entry <E> previous; // Entry (E element, Entry <E> next, entry <E> previous) {this. element = element; this. next = next; this. previous = previous ;}}

After the preceding non-argument constructor is executed, the empty annular two-way linked list is formed as follows:

The upper-left corner is previous, and the lower-right corner is next.

2.2 add an object to the consumer list (add (E ))

Implementation Method:

strList0.add("hello");

Source code:

/*** Add a new node at the end of the linked list. The data encapsulated by the new node is e */public boolean add (E e) {addBefore (e, header ); // Add a new node at the end of the linked list, and the data encapsulated by the new node is e return true ;}
/** Add a new node after specifying the node entry in the linked list. The data encapsulated by the new node is e */private Entry <E> addBefore (E e, Entry <E> entry) {Entry <E> newEntry = new Entry <E> (e, entry, entry. previous); newEntry. previous. next = newEntry; // The next node of the previous node of the new node is the newEntry of the new node. next. previous = newEntry; // The previous node of the next node of the new node is the size ++ of the new node; // The number of elements in the linked list + 1 modCount ++; // The same as the ArrayList, used to check whether the add and remove operations return newEntry ;}

The new circular two-way linked list after an element is added is as follows:

On the basis of the above, after calling add (E) Again, the new circular two-way linked list is as follows:

Here, you can view the source code of add (E) by combining the code comments and images.

Note: to add elements, you do not need to consider array expansion and array replication. You only need to create a new object, but you need to modify the attributes of the first and second objects.

2.3 obtain a single object in the listing list (get (int index ))

Implementation Method:

StrList. get (0); // Note: The subscript starts from 0.

Source code:

/*** Return the data whose index value is the index node. The index starts from 0. */public E get (int index) {return entry (index). element ;}
/*** Get the node at the specified index location (which requires a traversal table) */private Entry <E> entry (int index) {// index: 0 ~ Size-1 if (index <0 | index> = size) throw new IndexOutOfBoundsException ("Index:" + index + ", Size:" + size ); entry <E> e = header; // header node: if (index <(size> 1), both the header node and the End Node )) {// index <size/2 indicates that the index is in the first half of the linked list and is searched for (int I = 0; I <= index; I ++) e = e. next;} else {// index> = size/2, it means that the index is in the second half of the chain table, find for (int I = size; I> index from the back; I --) e = e. previous;} return e ;}

Note:

  • The linked list node needs to be searched by index, but the array does not.
  • Header nodes are both header nodes and tail nodes
  • To search for a two-way linked list, first determine whether the index value is smaller than size/2. If it is smaller than, it starts from the header node and searches for it from the past. If it is greater than or equal to, it starts from the header node, search from the back
  • Size> 1. Shifts one digit to the right by dividing by 2. Shifts one digit to the left by two.

2.4 modifyListing listData of the specified index node: set (int index, E element)

Usage:

strList.set(0, "world");

Source code:

/*** Modify the data of the node on the index at the specified index location to element */public E set (int index, E element) {Entry <E> e = entry (index ); // find the node E oldVal = e. element; // obtain the old value e. element = element; // assign the new value to the element attribute return oldVal of the node; // return the old value}

Note: view the preceding entry (int index)

2.5 DeleteShortlistObjects in

2.5.1. remove (Object o)

Usage:

strList.remove("world")

Source code:

/*** Delete the first node whose specified metadata is o */public boolean remove (Object o) {if (o = null) {// Delete the first null from the past/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 ;}
/** Delete node e */private E remove (Entry <E> e) {// the header node cannot be deleted if (e = header) throw new NoSuchElementException (); E result = e. element; // adjust the pointer of the front and back nodes to be deleted to point to e. previous. next = e. next; e. next. previous = e. previous; // The three attributes of the element to be deleted are left empty. next = e. previous = null; e. element = null; size --; // size-1 modCount ++; return result ;}

Note:

  • The header node cannot be deleted.

 2.5.2, remove (int index)

Usage:

strList.remove(0);

Source code:

/*** Delete the node of the specified index */public E remove (int index) {return remove (entry (index ));}

Note:

  • Remove (entry (index) See above
  • Remove (Object o) requires a traversal table, and remove (int index) also requires

 2.6 determine whether an object exists in the consumer list (Contains (E))

Source code:

/*** Whether the linked list contains the node of the specified data o */public boolean contains (Object o) {return indexOf (o )! =-1 ;}
/*** From the header, search for the first index with an o */public int indexOf (Object o) {int index = 0; if (o = null) {// starting from the header, search for the first index containing null for (Entry e = header. next; e! = Header; e = e. next) {if (e. element = null) return index; index ++ ;}} else {for (Entry e = header. next; e! = Header; e = e. next) {if (o. equals (e. element) return index; index ++ ;}} return-1 ;}

Note:

  • IndexOf (Object o) returns the index of the first appearing element o

2.7 TraversalShortlistObject (iterator () in ())

Usage:

        List<String> strList = new LinkedList<String>();        strList.add("jigang");        strList.add("nana");        strList.add("nana2");                Iterator<String> it = strList.iterator();        while (it.hasNext()) {            System.out.println(it.next());        }

Source code: The iterator () method is implemented in the AbstractSequentialList of the parent class,

    public Iterator<E> iterator() {        return listIterator();    }

The listIterator () method is implemented in the parent class javasactlist,

    public ListIterator<E> listIterator() {        return listIterator(0);    }

The listIterator (int index) method is implemented in the parent class javasactlist,

    public ListIterator<E> listIterator(final int index) {        if (index < 0 || index > size())            throw new IndexOutOfBoundsException("Index: " + index);        return new ListItr(index);    }

This method returns an internal class ListItr object of AbstractList.

ListItr:

    private class ListItr extends Itr implements ListIterator<E> {        ListItr(int index) {            cursor = index;        }

The above class is not complete. It inherits the internal class Itr and extends some other methods (eg. the forward lookup method hasPrevious () and so on), as for hasNext ()/next () and other methods still come from Itr.

Itr:

Private class Itr implements Iterator <E> {int cursor = 0; // tag bit: indicates which element to traverse int expectedModCount = modCount; // tag bit: used to determine whether the add and remove operations are performed during the traversal process. // check whether the object array has a public boolean hasNext () {return cursor! = Size (); // If cursor = size, the traversal is complete. The last element is traversed.} // obtain the public E next () element () {checkForComodification (); // checks whether the add or remove operations occur during traversal. try {E next = get (cursor ++); return next ;} catch (IndexOutOfBoundsException e) {// capture the IndexOutOfBoundsException checkForComodification (); throw new NoSuchElementException ();} // detects the traversal process, whether action such as add or remove has occurred. final void checkForComodification () {if (mod Count! = ExpectedModCount) // The add and remove operations occur. You can view the source code of add and other operations. modCount ++ throw new ConcurrentModificationException ();} appears ();}}

Note:

  • The above Itr removes a method and attribute that cannot be used at this time.
  • The get (int index) method here is shown in 2.3.

Iii. Summary

  • The linked list is implemented based on a circular two-way linked list with no capacity limit.
  • You do not need to expand the capacity when adding elements (directly create a new node and adjust the pointer attribute pointing to the front and back nodes of the inserted nodes)
  • Thread Security
  • Get (int index): a time-series table is required.
  • Remove (Object o) requires a traversal table
  • Remove (int index) requires a traversal table
  • Contains (E) requires a time series table

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.