In-depth analysis of iterator, vector, arraylist, and list in Java

Source: Internet
Author: User

Linear tables, linked lists, and hash tables are common data structures. During Java Development, JDK provides a series of corresponding classes for us to implement basic data structures. These classes are in the Java. util package. This article attempts to explain the functions of each class and how to use these classes correctly through a simple description.

Collection <br/> collections list <br/> │ ├ linkedlinkedlist <br/> │ ├ arraylist <br/> │ vector <br/> │ └ stack <br/> tables set <br/> Map <br/> using hashtable <br/> using hashmap <br/> using weakhashmap

 

Collection Interface

Collection is the most basic collection interface. A collection represents a group of objects, that is, collection elements.
(Elements ). Some collections allow the same elements while others do not. Some can be sorted, while others cannot. Java
The SDK does not provide classes that directly inherit from the collection. The classes provided by the Java SDK all inherit from the "sub-interfaces" of the collection, such as list and set.

All classes that implement the collection interface must provide two standard constructor: A non-parameter constructor is used to create an empty collection with one
The constructor of the collection parameter is used to create a new
Collection. The new collection has the same elements as the imported collection. The next constructor allows you to copy a collection.

How to traverse every element in the collection? Regardless of the actual type of collection, it supports an iterator () method. This method returns an iterator, and each element in the collection can be accessed one by one using this iterator. The typical usage is as follows:

Iterator it = collection. iterator (); // obtain an iterator <br/> while (it. hasnext () {<br/> Object OBJ = it. next (); // obtain the next element <br/>}

The two interfaces derived from the collection interface are list and set.

 

Traverse a set in iterator Mode

The iterator mode is a standard access method used to traverse collection classes. It can abstract the access logic from a collection class of the same type to avoid exposing the internal structure of the set to the client.

For example, if the iterator is not used, the index is used to traverse an array:

For (INT I = 0; I <array. Size (); I ++) {... get (I )...}

 

To access a linked list, you must use the while loop:

While (E = E. Next ())! = NULL) {... e. Data ()...}

 

The mystery is that the client does not maintain the "Pointer" of the traversal set. All internal states (such as the current element location and whether there is any next element) are maintained by iterator, this iterator is generated by the collection class through the factory method, so it knows how to traverse the entire set.

The client never directly deals with the collection class. It always controls the iterator and sends the "forward", "backward", "Get current element" command to it to indirectly traverse the entire set.

First, let's take a look at the definition of the Java. util. iterator interface:

Public interface iterator {Boolean hasnext (); object next (); void remove ();}

 

The traversal can be completed by relying on the first two methods. The typical code is as follows:

For (iterator it = C. iterator (); it. hasnext ();) {object o = it. Next (); // operations on o ...}

 

In jdk1.5, the above Code is also simplified in syntax:

// Type is a specific type, such as string. For (type T: C) {// t operation ...}

The iterator types returned by each collection class may be different, array may return arrayiterator, and set may return
Setiterator and tree may return treeiterator, but they all implement the iterator interface. Therefore, the client does not care about which
Iterator. It only needs to obtain this iterator interface, which is the power of object-oriented.

Iterator source code analysis

Let's take a look at how abstracylist creates an iterator. First, abstractlist defines an inner class ):

Private class itr implements iterator {...}

 

The iterator () method is defined as follows:

Public iterator () {return New itr ();}

 

Therefore, the client does not know the real type of iterator obtained through iterator it = A. iterator.

Now we are concerned about how the private itr class traverses javasactlist:

Private class itr implements iterator {int cursor = 0; int lastret =-1; int expectedmodcount = modcount ;}< br/>

 

The itr class traverses three int variables (and an implicit abstractlist reference). The cursor is the position of the element in the next () call and calls next () for the first time () returns the element with an index of 0. Lastret records the position of the last cursor, so it is always 1 less than cursor.

The number of elements in the variable cursor and set determines hasnext ():

Public Boolean hasnext () {return cursor! = Size () ;}< br/>

 

The method next () returns the element whose index is cursor, and then modifies the values of cursor and lastret:

Public object next () {checkforcomodification (); try {object next = get (cursor); lastret = cursor ++; return next;} catch (indexoutofboundsexception e) {checkforcomodification (); throw new nosuchelementexception ();}}

 

Expectedmodcount indicates the expected modcount value, which is used to determine whether the combination has been modified during the traversal process. Abstractlist contains
Modcount variable. Its initial value is 0. When the set is modified once (the add, remove, and other methods are called), modcount is added to 1. Therefore, if modcount is not
Changed, indicating that the set content has not been modified.

When itr is initialized, expectedmodcount is used to record the modcount variable of the set. It then detects the value of modcount where necessary:

Final void checkforcomodification () {If (modcount! = Expectedmodcount) throw new concurrentmodificationexception ();}

 

If modcount is different from the value of the initial record in expectedmodecount, it indicates that the set content has been modified and concurrentmodificationexception is thrown.

This concurrentmodificationexception is runtimeexception and should not be captured on the client. If this exception occurs, it indicates that there is a problem with programming code. You should check the code carefully instead of ignoring it in catch.

However, it is no problem to call the remove () method of iterator to delete the current element, because the expectedmodcount and modcount values are automatically synchronized in this method:

Public void remove (){... abstractlist. this. remove (lastret );... // After the remove () method of the set is called, The expectedmodcount: expectedmodcount = modcount;...} is reset ;...}

 

To ensure the smooth completion of the traversal process, you must ensure that the content of the set is not changed during the traversal process (except for the remove () method of iterator). Therefore, to ensure reliable traversal, you can only use this set in one thread or synchronize the traversal code in multiple threads.

Finally, a complete example is provided:

Collection c = new arraylist (); C. add ("ABC"); C. add ("XYZ"); For (iterator it = C. iterator (); it. hasnext ();) {string S = (string) it. next (); system. out. println (s );}

 

If you replace the arraylist of the first line of code with a struct list or vector, the remaining code can be compiled without changing the line, and the function remains unchanged. This is the principle of abstract programming: the minimum dependence on a specific class.

List Interface

List is an ordered collection, which can be used to precisely control the insert position of each element. You can use an index (the position of an element in the list, similar to an array subscript) to access the elements in the list, which is similar to an array in Java.

Unlike the set mentioned below, the list can have the same element.

In addition to the iterator () method that is essential to the Collection interface, list also provides a listiterator () method that returns
Listiterator interface. Compared with the standard iterator interface, listiterator has some add () and other methods, allowing you to add, delete, and set elements,
It can also traverse forward or backward.

Common classes that implement the list interface include the list, arraylist, vector, and stack.

Sort list class

The listlist interface allows null elements. In addition, the tranquility list provides additional
Get, remove, insert method in
The header or tail of the sequence list. These operations enable the queue list to be used as a stack, queue, or two-way Queue (deque ).

Note that the synchronized list method is not available. If multiple threads access a list at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronized list when creating a list:

List list = collections. synchronizedlist (new collections list (...));

 

Arraylist class

Arraylist implements an array of variable sizes. It allows all elements, including null. Arraylist is not synchronized.

Size, isempty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear.

Each arraylist instance has a capacity, that is, the size of the array used to store elements. This capacity can automatically increase as new elements are added,
The growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensurecapacity method before insertion to increase the arraylist capacity to improve the insertion efficiency.

Like the synchronized list, arraylist is also non-synchronous (unsynchronized ).

Vector

The vector is very similar to the arraylist, but the vector is synchronized. Iterator created by vector, although
The
Iterator is the same interface, but because vector is synchronized, when an iterator is created and is in use, another thread changes the state of the vector (for example
For example, some elements are added or deleted ).

 

 

 

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.