Java set (2): List

Source: Internet
Author: User

Java set (2): List

The previous section describes the overall situation of Java collections. This section describes the specific classes. Here we will not only introduce the usage of classes, but also try to analyze the implementation of classes from the perspective of source code. This section describes the List interface and implementation class, that is, the linked List listing and the array List ArrayList.

1 List interface and abstract class

The List interface extends the self-Collection interface, which designs some methods suitable for List operations. List is an ordered set. elements can be added to a specific position in the container.

After using javac to compile the List. java source code, you can use javap to decompile the source code to obtain the specific information of the interface, as shown in the following figure:

Compiled from "List.java"public interface java.util.List
 
   extends java.util.Collection
  
    {  public abstract int size();  public abstract boolean isEmpty();  public abstract boolean contains(java.lang.Object);  public abstract java.util.Iterator
   
     iterator();  public abstract java.lang.Object[] toArray();  public abstract 
    
      T[] toArray(T[]);  public abstract boolean add(E);  public abstract boolean remove(java.lang.Object);  public abstract boolean containsAll(java.util.Collection
     );  public abstract boolean addAll(java.util.Collection
     );  public abstract boolean addAll(int, java.util.Collection
     );  public abstract boolean removeAll(java.util.Collection
     );  public abstract boolean retainAll(java.util.Collection
     );  public void replaceAll(java.util.function.UnaryOperator
     
      );  public void sort(java.util.Comparator
      );  public abstract void clear();  public abstract boolean equals(java.lang.Object);  public abstract int hashCode();  public abstract E get(int);  public abstract E set(int, E);  public abstract void add(int, E);  public abstract E remove(int);  public abstract int indexOf(java.lang.Object);  public abstract int lastIndexOf(java.lang.Object);  public abstract java.util.ListIterator
      
        listIterator(); public abstract java.util.ListIterator
       
         listIterator(int); public abstract java.util.List
        
          subList(int, int); public java.util.Spliterator
         
           spliterator();}
         
        
       
      
     
    
   
  
 
The List interface provides these methods, most of which are Abstract, but some are not. These methods are the default method added in JDK 1.8, such as the sort method.

The List interface provides random access methods, such as the get (int) method, but the List does not matter whether a specific implementation of these methods is efficient. To avoid high-cost random access operations, Java SE 1.4 introduces a tag interface RandomAccess. This interface does not have any method, but can be used to check whether a specific set supports efficient random access:

if(c instanceof RandomAccess){    use random access algorighm}else{    use sequential access algorithm}
ArrayList implements this interface.

Routine methods in the List interface are implemented in the abstract class AbstractList, so that they do not need to be implemented in a specific class, such as the isEmpty method and the contains method. These routine methods are simple and have obvious meanings. For classes with random access elements (such as ArrayList), the abstract class is inherited first.

In the AbstractList abstract class, there is an important field called modCount:

protected transient int modCount = 0;

This field can be used to track the number of structural changes in the list. What are structural changes? Changes the length of a list, such as adding or deleting a list. Modifying the value of a node is not a structural modification.

This field is very useful in later iterators. The iterator can use this field to detect concurrent modifications. This issue will be described in the javaslist class.

The abstract class AbstractSequentialList implements some methods in the List interface. For classes (such as the sequential List) that access elements in sequence, this abstract class is preferentially inherited.

2 linked list: Linked List

A linked list is a data structure that everyone is very familiar. The linked list solves the problem that the efficiency of inserting and deleting elements in the array list is too low. The insertion and deletion of the linked list is very efficient.

The linked list stores each object in an independent node. In Java, A sort list linked list. Each node has a reference to a forward node in addition to a reference to a backward node. That is to say, a sort list is a two-way linked list.

The shortlist class has three fields: Size, header knot, and end node:

transient int size;transient Node
 
   first;transient Node
  
    last;
  
 

There are two constructors, one with no parameters and one with parameters:

public java.util.LinkedList();public java.util.LinkedList(java.util.Collection
 );

The no-argument constructor constructs an empty linked list. The constructor contains parameters to construct a linked list based on a collection.

2.1 Node Internal class

The worker list class defines a Node Internal class to represent a node. The class is defined as follows:

private static class Node
  
    {    E item;    Node
   
     next;    Node
    
      prev;    Node(Node
     
       prev, E element, Node
      
        next) {        this.item = element;        this.next = next;        this.prev = prev;    }}
      
     
    
   
  
This is a static internal class and there is no external reference. This class has three fields: value, reference of the pre-order node, reference of the Post-order node, there is also a constructor method, the definition is simple.

To create a Node, you can:

Node
  
    node=new Node<>(pre,item,next);
  

Pre and next are references of the forward and backward nodes, respectively.

2.2 Basic Method of linked list operation

Since it is a linked list, the addition and deletion of linked list nodes are indispensable. In the shortlist class, six basic linked list operations are provided. These methods modify the structure of the linked list. Therefore, the modCount field in the shortactlist class is changed, the six methods are as follows:

Private void linkFirst (E); // The node added to the head of the linked list as the header node void linkLast (E ); // Add a fixed value node to the end of the linked list as the void linkBefore (E, java. util. worker list $ Node
  
   
); // Insert a private E unlinkFirst (java. util. writable list $ Node before a given Node
   
    
); // Delete the header Node and return the value of the header Node private E unlinkLast (java. util. writable list $ Node
    
     
); // Delete the end Node and return the value of the End Node E unlink (java. util. shortlist $ Node
     
      
); // Delete a given Node
     
    
   
  
These methods are private (or private in the package), so they can be called tool methods. All structural modification operations in the javaslist class are implemented based on these six methods.

These six methods are the basic operations of the linked list, and the code is relatively simple, but the implementation can look at the writing of the source code implementer, which is helpful for self-programming:

    /**     * Links e as first element.     */    private void linkFirst(E e) {        final Node
  
    f = first;        final Node
   
     newNode = new Node<>(null, e, f);        first = newNode;        if (f == null)            last = newNode;        else            f.prev = newNode;        size++;        modCount++;    }    /**     * Links e as last element.     */    void linkLast(E e) {        final Node
    
      l = last;        final Node
     
       newNode = new Node<>(l, e, null);        last = newNode;        if (l == null)            first = newNode;        else            l.next = newNode;        size++;        modCount++;    }    /**     * Inserts element e before non-null Node succ.     */    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++; } /** * Unlinks non-null first node f. */ private E unlinkFirst(Node
         
           f) { // assert f == first && 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; } /** * Unlinks non-null last node l. */ private E unlinkLast(Node
           
             l) { // assert l == last && 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; } /** * Unlinks non-null 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; }
               
              
             
            
           
          
         
        
       
      
     
    
   
  
2.3 list iterator: ListIterator Interface

A linked list is an ordered set. The position of each object is very important. The worker list. add method only adds nodes to the end. However, a large part of linked list operations need to add nodes to the center of the linked list. Since the iterator is the position in the number of seconds set, the iterator is responsible for adding such dependency positions. It makes sense to use an iterator to add elements to a naturally ordered set. For example, for unordered set, there is no add method in the Iterator interface. On the contrary, the ListIterator interface is provided in the Collection class library, where the add method is provided:

interface ListIterator
  
    extends Iterator
   
    {    void add(E element);    ...}
   
  
Unlike the add method in the Collection interface, this method does not return a boolean value because it assumes that the add operation always changes the linked list.

In addition to the hasNext and next methods, the ListIterator interface provides the following two methods:

E previous();boolean hasPrevious();
The two methods are used to reverse the traversal chain table, and previous returns the object that is crossed like next.

The listIterator method of the listIterator list class returns an iterator object:

ListIterator
  
    iter=list.listIterator();
  
When introducing interfaces, we know that we cannot instantiate an interface object, but we can declare an interface object and reference an instance of the class that implements this interface. Therefore, the listIterator method must return an instance of a class, and this class must implement this interface. The question is, what is this class?

This class is actually an internal class of the consumer list, that is, ListItr:

Compiled from "LinkedList.java"class java.util.LinkedList$ListItr implements java.util.ListIterator
  
    {  private java.util.LinkedList$Node
   
     lastReturned;  private java.util.LinkedList$Node
    
      next;  private int nextIndex;  private int expectedModCount;  final java.util.LinkedList this$0;  java.util.LinkedList$ListItr(java.util.LinkedList, int);  public boolean hasNext();  public E next();  public boolean hasPrevious();  public E previous();  public int nextIndex();  public int previousIndex();  public void remove();  public void set(E);  public void add(E);  public void forEachRemaining(java.util.function.Consumer
     );  final void checkForComodification();}
    
   
  
The above is also the result of javap decompilation. As you can see, this internal class implements the ListIterator interface and implements the method of this interface.

This is the key to understanding the iterator. We know that the iterator can be regarded as a position in the middle of two nodes. That is to say, for a chain table with n sizes, the iterator has n + 1 position:

| A | B |... | z |

In this example, the linked list represents 26 letters, and the iterator has 27 characters.

Here, the iterator is also visualized as the cursor. The next method is to move the cursor to the next position and return the elements that have just been crossed after dinner. Similarly, the previous method is the same, but it only shifts the left position, then return the elements that have just been crossed. The code for these two methods is as follows:

public E next() {    checkForComodification();    if (!hasNext())        throw new NoSuchElementException();    lastReturned = next;    next = next.next;    nextIndex++;    return lastReturned.item;}public E previous() {    checkForComodification();    if (!hasPrevious())        throw new NoSuchElementException();    lastReturned = next = (next == null) ? last : next.prev;    nextIndex--;    return lastReturned.item;}
The two methods first call the checkForComodifcation method to check for concurrent modifications. As mentioned above, modCount of javasactlist records the number of changes to the linked list, and each iterator maintains an independent counter through the following fields:

private int expectedModCount = modCount;
This field is initialized as the modCount modification times of the class. CheckForComodification checks whether the counter maintained by the iterator is equal to the modCount of the class. If not, a ConcurrentModificationException is thrown.

After the concurrent modification check is passed, the hasNext or hasPrevious method is called to check whether the elements are to be accessed. The ListItr class has a nextIndex field:

private int nextIndex;
This field maintains the current position of the iterator. Of course, for the iterator list, because the iterator points to the middle of two elements, two indexes can be generated simultaneously: the nextIndex method returns the integer index of the element when the next method is called. The previusindex method returns the index of the element when the next method is called, which is 1 less than nextIndex.

The hasNext and hasPrevious methods are used to check whether nextIndex and previusindex are in the correct range and whether the elements are to be accessed.

The ListItr class also has two fields:

private Node
  
    lastReturned;private Node
   
     next;
   
  
LastReturned is used to save the last returned node. next is the next element of the iterator position. It can also be seen as the next element of the cursor (The next element is always the element on the right of the cursor ). After the next method is called, The cursor shifts one position to the right, crosses the node saved in the next field, and then updates the values of the two fields, that is, the next is changed to lastReturned, and next is the next element, then nextIndex increases by 1.

Compared with the next operation, previous is equivalent to moving the cursor to the left. When updating lastReturned and next, you need to consider whether next is null. If next is null, The iterator is in the last position when previous is not executed. Therefore, after previous is executed, next should be the last node of the linked list; if next is not null, then, next is updated to the forward node of next. LastReturned is the element that the cursor has just crossed, that is, the current next node. At this time, the lastReturned and next nodes point to the same element.

The ListItr class has three methods for modifying the linked list: add, remove, and set. The add and remove methods change the iterator position because the two methods modify the structure of the linked list. The set method does not modify the iterator position because it does not modify the chain table structure.

The code for these three methods is as follows:

public void remove() {    checkForComodification();    if (lastReturned == null)        throw new IllegalStateException();    Node
  
    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++;}
  
It is worth noting that the remove Method. Each time you call the remove Method, lastReturned is set to null. That is to say, if the remove method is called consecutively, an IllegalStateException exception will be thrown during the second call. Therefore, the remove operation must be followed by the next or previous operation.

Now we have introduced the basic methods of the ListIterator interface. You can add or delete elements from the elements in the two successive links.

Remember: The ListIterator iterator provides the operation to add or delete nodes at any location of the linked list. The add method of the class itself can only be added at the end.

2.4 Random Access

In the Java class library, there are also a lot of theoretically controversial methods. The linked list does not support fast random access. If you want to view the nth element in the linked list, you must start from scratch and overwrite n-1 elements. There is no shortcut. For this reason, when the program needs to use an integer index to access elements, the linked list is generally not used.

Even so, the shortlist class also provides a get method to access a specific element:

LinkedList
  
    list=...;String s=list.get(n);
  
Of course, this method is not very efficient. We should never use this misleading random access method to traverse a table. The following code is very inefficient:

For (int I = 0; I
  
   

Each time you search for an element, you must search again from the beginning. The sorted list object does not process any cached location information at all.

In fact, in the shortlist class, the get method will determine the current position closer to the header and the end, and then determine whether to traverse from left to right or from right to left.

2.5 example

The following code demonstrates the basic operations of the sort list class. It simply creates two linked lists, merges them together, deletes an element from each other in the second linked list, and finally tests the removeAll method:

import java.util.*;public class LinkedListTest {    public static void main(String[] args) {        List
    
      a=new LinkedList<>();        a.add("A");        a.add("C");        a.add("E");        List
     
       b=new LinkedList<>();        b.add("B");        b.add("D");        b.add("F");        b.add("G");        ListIterator
      
        aIter=a.listIterator();        Iterator
       
         bIter=b.iterator();        while(bIter.hasNext()){            if(aIter.hasNext())aIter.next();            aIter.add(bIter.next());        }        System.out.println(a);        bIter=b.iterator();        while(bIter.hasNext()){            bIter.next();            if(bIter.hasNext()){                bIter.next();                bIter.remove();            }        }        System.out.println(b);        a.removeAll(b);        System.out.println(a);    }}
       
      
     
    
The result is as follows:


3. array list: ArrayList

This section describes the List interface and the List class that implements this interface. The List interface is used to describe an ordered set, and the position of each element in the set is very important. There are two access element protocols: one is to use the iterator, and the other is to use the get and set methods to randomly access each element. The latter is not applicable to linked lists, but is useful for arrays. The Collection class library provides an ArrayList class that everyone is very familiar with. This class also implements the List interface. The ArrayList class encapsulates an array of dynamically distributed objects.

The Java Collection class library also contains a dynamic array: Vector class. However, all methods of this class are synchronized, and two threads can safely access a Vector object. However, if a thread accesses the Vector, the code will consume a lot of time in synchronization. The ArrayList method is not synchronous. Therefore, ArrayList is used if synchronization is not required.

The ArrayList details the implementation of classes and the use of methods.

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.