Java (article 30) ----- Iterator, java ----- iterator

Source: Internet
Author: User
Tags concurrentmodificationexception

Java (article 30) ----- Iterator, java ----- iterator

Iteration is no stranger to Java. We often use the iterative interfaces provided by JDK to iterate Java sets.

Iterator iterator = list.iterator();        while(iterator.hasNext()){            String string = iterator.next();            //do something        }

Iteration can be simply understood as traversal. It is a method class that standardizes all objects in various containers. It is a typical design model. 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. This is the case when there is no iterator. As follows:

For arrays, we use subscript for processing:

int[] arrays = new int[10];for(int i = 0 ; i < arrays.length ; i++){       int a = arrays[i];       //do something   }

This is the case for ArrayList:

List<String> list = new ArrayList<String>();   for(int i = 0 ; i < list.size() ;  i++){      String string = list.get(i);      //do something   }

For both methods, we always know the internal structure of the set in advance. The access code is closely coupled with the set itself, and the access logic cannot be separated from the Collection class and client code. At the same time, each set corresponds to a Traversal method, and client code cannot be reused. In practical applications, it is quite troublesome to integrate the above two sets. To solve the above problem, the Iterator mode is born, and it always uses the same logic to traverse the set. So that the client itself does not need to maintain the internal structure of the set, and all internal states are maintained by Iterator. 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.

The above is just a brief description of the Iterator mode. Let's take a look at the Iterator interface in Java and see how it is implemented.

1. java. util. Iterator

In Java, Iterator is an interface that only provides the basic iteration rules. In JDK, it defines the Iterator for the collection iteration. The iterator replaces Enumeration in Java Collections Framework. There are two differences between the iterator and enumeration:

1. The iterator allows callers to remove elements from the collection point pointed to by the iterator during iteration using well-defined semantics.

2. The method name has been improved.

Its interface is defined as follows:

public interface Iterator {  boolean hasNext();  Object next();  void remove();}

Where:

Object next (): return the reference of the element just crossed by the iterator. The returned value is the Object, which must be forcibly converted to the desired type.

Boolean hasNext (): determines whether there are any accessible elements in the container.

Void remove (): deletes the elements that have just been crossed by the iterator.

For us, we only need to use the next () and hasNext () Methods to complete the iteration. As follows:

for(Iterator it = c.iterator(); it.hasNext(); ) {  Object o = it.next();   //do something}

I have explained that Iterator has a great advantage, that is, we do not have to know the internal results of the set. The internal structure and status of the set are maintained by Iterator. hasNext () and next () to determine and obtain the next element. We don't have to worry about the specific internal implementation.But as a qualified programmer, it is very necessary for us to figure out the implementation of Iterator.Next we will analyze the source code of ArrayList.

2. Implementation of Iterator for each set

The following is an analysis of the Iterator Implementation of ArrayList. If we understand the data structure and internal implementation of ArrayList, Hashset, and TreeSet, we are confident about how they implement Iterator. Because the internal implementation of ArrayList uses arrays, we only need to record the index of the corresponding location. The implementation of this method is relatively simple.

2.1 Iterator Implementation of ArrayList

In ArrayList, an internal class Itr is defined first, which implements the Iterator interface, as follows:

private class Itr implements Iterator<E> {    //do something}

The iterator () method of ArrayList is implemented as follows:

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

Therefore, the internal Itr () class is returned by using the ArrayList. iterator () method. Therefore, we need to consider the implementation of the internal Itr () class:

Three int-type variables are defined in Itr: cursor, lastRet, and expectedModCount. Cursor indicates the index location of the next element, and lastRet indicates the index location of the previous element.

int cursor;             int lastRet = -1;     int expectedModCount = modCount;

According to the definition of cursor and lastRet, lastRet is always one less than cursor, so the hasNext () implementation method is very simple. You only need to judge whether the cursor and lastRet are equal.

public boolean hasNext() {    return cursor != size;}

The next () implementation is actually relatively simple. You only need to return the elements at the cursor index location, and then modify cursor and lastRet,

Public E next () {checkForComodification (); int I = cursor; // record the index location if (I> = size) // if the retrieved element is greater than the number of set elements, throw new NoSuchElementException (); Object [] elementData = ArrayList. this. elementData; if (I> = elementData. length) throw new ConcurrentModificationException (); cursor = I + 1; // cursor + 1 return (E) elementData [lastRet = I]; // lastRet + 1 and return the element at cursor}

CheckForComodification () is used to determine whether the number of changes to the set is valid, that is, to determine whether the set has been modified during the traversal process. I have already explained this in java (ii) ----- ArrayList. ModCount is used to record the number of modifications to the ArrayList set. It is initialized to 0. Each time the set is modified once (internal update is not counted for the structure modification), such as add and remove methods, modCount + 1, so if modCount remains unchanged, the set content is not modified. This mechanism is mainly used to implement the fast failure mechanism of the ArrayList set. In the Java Collection, a large part of the set has a fast failure mechanism, which is not described here. Therefore, to ensure that no errors occur during the traversal process, we should ensure that the structure of the set is not modified during the traversal process (except for the remove Method of course), and an exception error occurs, we should check whether the program has an error rather than making a catch request.

       final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }

The remove () method is implemented. It calls the remove () method of ArrayList to delete the lastRet position element and modify modCount.

public void remove() {            if (lastRet < 0)                throw new IllegalStateException();            checkForComodification();            try {                ArrayList.this.remove(lastRet);                cursor = lastRet;                lastRet = -1;                expectedModCount = modCount;            } catch (IndexOutOfBoundsException ex) {                throw new ConcurrentModificationException();            }        }

Here I will explain the implementation of Iterator in ArrayList. If you are interested in implementation of Iterator in Hashset, TreeSet, and other sets, I think that before studying the source code of these sets, it is necessary to have a clear understanding of the data structure of the set, so as to get twice the result with half the effort !!!!

---------------------------------------------------------
-- Original from: http://cmsblogs.com /? P = 1180. Respect the author's achievements. For more information, see the source!

-- Personal site: http://cmsblogs.com


What is the specific role of Iterator in JAVA?

Iterator pattern)
I. Introduction
The term "iteration" is no stranger to those familiar with Java. We often use the iterative interface provided by JDK to traverse java collections:
Iterator it = list. iterator ();
While (it. hasNext ()){
// Using "it. next ();" do some businesss logic
}
This is a good example of the application of the iterator mode.
Ii. Definition and Structure
The Iterator mode is also called the Cursor mode. GOF defines a method to access each element in a container object without exposing the internal details of the object.
From the definition, we can see that the iterator mode is generated for containers. Obviously, accessing container objects involves Traversal Algorithms. You can plug the Traversal method into the container object in one brain; or you don't provide any Traversal Algorithms at all, so that the container users can implement them themselves. Both cases seem to be able to solve the problem.
However, in the previous case, the container is subject to too many functions. It is not only responsible for maintaining the elements (adding, deleting, and so on) in its own "container", but also provides interfaces for Traversing itself; in addition, you cannot traverse the same container object at the same time because the traversal status is saved. The second method saves trouble, but exposes the internal details of the container.
The appearance of the iterator mode solves the disadvantages of the above two situations. Let's take a look at the real face of the iterator mode.
The iterator mode consists of the following roles:
1) Iterator role (Iterator): The Iterator role defines interfaces for accessing and traversing elements.
2) Concrete Iterator: The specific Iterator role must implement the Iterator interface and record the current position in the traversal.
3) Container role: the Container role is responsible for providing interfaces for creating specific iterator roles.
4) Concrete Container: The Container role implements the interface for creating a specific iterator role. This specific iterator role is related to the structure of the Container.
The class diagram of the iterator mode is as follows:

It can be seen from the structure that the iterator mode adds the iterator role between the customer and the container. The addition of the iterator role can avoid the exposure of internal details of the container, and also make the design symbol "single responsibility principle ".
Note: In the iterator mode, the specific iterator role is coupled with the specific container role-the traversal algorithm is closely related to the internal details of the container. In order to remove the customer program from the dilemma of coupling with the specific iterator role, and to avoid modifications to the customer program due to the replacement of the specific iterator role, the iterator mode abstracts the specific iterator role, making the customer program more general and reusable. This is called a multi-state iteration.
Iii. Example
Since the iterator mode itself is relatively loose, the specific implementation is varied. Let's just take an example here. We cannot present the implementation methods one by one. For this reason, let's first list the implementation methods of the iterator mode.
1. The iterator role defines the traversal interface, but does not specify who controls the iteration. In Java collection Applications, traversal processes are controlled by client programs and called external iterators. Another implementation method is to control iterations by the iterator itself, it is called an internal iterator. The external iterator is more flexible and powerful than the internal iterator, and the internal iterator has poor availability in the java language environment.
2. In the iterator mode, there is no rule on who will implement the traversal algorithm. It seems that it should be implemented in the iterator role. Because it is easy to use different Traversal Algorithms on a container, it is also convenient to apply a traversal algorithm to different containers. But in this way, container encapsulation is destroyed. The Container role must expose its own private attributes. in java, this means that its private attributes are disclosed to other classes.
Let's put it in the container role. In this way, the iterator role is shelved to only store a function that traverses the current position. However, the traversal algorithm is closely bound to a specific container.
In Java Collec... the remaining full text>

In JAVA, the Iterator method has two value methods, for example, Iterator <Student> it = listiterator ();

Iterator is generated by the collection class through the factory method. There are two access methods for record in the method, one is sequential storage, and the other is linked storage. If you use for (int I) [for example, the variable in for is I] and then get, the lower the value of I, the more slow it is (because he needs to find all the values in the future and know that the subscript is I), but it is different with next, no matter how deep your value is, his next pointer always points to the next one at the current position. For example, if you are looking for the value of the 1W, when you use for to 9999 (all consumption before 9999 is ignored temporarily), you are going to find 10,000th, we are sure we want to find the subscript 10000. Although it is now 9999, he still needs to find it from the beginning. If it is next, because now it is 9999, and his next is just 10000, it will soon be. Let me give you an example. There are 10 layers of books. Now you have found 9th layers of mathematics. I want the tenth floor of the book. In the first case, you have to start from scratch, the number of three layers is 10th, but next, you will know that the next one is what I want. (The previous 10 is a loop of other external variables, and next is inside the iterator.) The level is limited. I don't know if it is correct. I understand it in this way. Haha

You should ask the advantages and disadvantages of the get method of the set to traverse the value and the iterator of the set.

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.