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 )...}
Accessing a linked list)The while loop must also be used.:
While (e = e. next ())! = Null) {... e. data ()...}
AboveBoth methods the client must know the internal structure of the set in advance.The access code and the set itself are tightly coupled, and the access logic cannot be separated from the collection class and client code. Each set corresponds to a traversal method, and the client code cannot be reused.
What's even more frightening is that if you need to replace ArrayList with a future list, all the original client code must be rewritten.
To solve the above problem, the Iterator mode always uses the same logic to traverse the set:
For (Iterator it = c. iterater (); it. hasNext ();){...}
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", "Take the 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 (but limited to read-only, if you need to remove it, use iterator directly ):
// 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, 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 is. It only needs to obtain this Iterator interface, which is the power of object-oriented.
----------------------------------------------------------------
The parameter http://www.blogjava.net/EvanLiu/archive/2008/08/31/224453.html of java. util. ConcurrentModificationException occurs during traversal.
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 )...}
Accessing a linked list)The while loop must also be used.:
While (e = e. next ())! = Null) {... e. data ()...}
AboveBoth methods the client must know the internal structure of the set in advance.The access code and the set itself are tightly coupled, and the access logic cannot be separated from the collection class and client code. Each set corresponds to a traversal method, and the client code cannot be reused.
What's even more frightening is that if you need to replace ArrayList with a future list, all the original client code must be rewritten.
To solve the above problem, the Iterator mode always uses the same logic to traverse the set:
For (Iterator it = c. iterater (); it. hasNext ();){...}
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", "Take the 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 (but limited to read-only, if you need to remove it, use iterator directly ):
// 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, Set May return SetIterator, Tree may return TreeIterator, but they all implement the Iterator interface. Therefore, the client does not care about which Iterator it is. It only needs to obtain this Iterator interface, which is the power of object-oriented.
----------------------------------------------------------------
The parameter http://www.blogjava.net/EvanLiu/archive/2008/08/31/224453.html of java. util. ConcurrentModificationException occurs during traversal.
If you want to use foreach to traverse the set of custom classes, the custom class usually needs to implement the implement iterable interface. this interface defines the Iterator <T> iterator () method. sometimes this iterator method can use the set attributes in the class. iterator () returns.
Public class Teacher implements Iterable {
Private String name;
Private int age;
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
Public Iterator iterator (){
Return new Itr ();
}
Public static void main (String [] args ){
Teacher t = new Teacher ();
T. setName ("aaaaaaa ");
T. setAge (23 );
For (Object o: t ){
System. out. println (o. toString ());
}
}
Private class Itr implements Iterator {
Private int cursor = 0; // attribute index
Private Field [] fields = Teacher. class. getDeclaredFields (); // attribute array
Public boolean hasNext (){
Return cursor! = (Teacher. class. getDeclaredFields (). length );
}
Public Object next (){
Object o = null;
Try {
Fields [cursor]. setAccessible (true); // allows the internal class to access the private attribute value of the external class
O = fields [cursor]. getName () + "" + fields [cursor]. get (Teacher. this );
Cursor ++;
} Catch (Exception e ){
System. out. println (e );
}
Return o;
}
Public void remove (){
// TODO Auto-generated method stub
}
}
}
Import java. util. Iterator;
// Test class
Public class Exec {
Public static void main (String [] args) throws Exception {
// Create a student collection class
Students students = new Students (10 );
// Use the for each statement to iterate every element of the student set class
For (Object obj: students ){
Student stu = (Student) obj;
System. out. println (stu. getSid () + ":" + stu. getName ());
}
}
}
// Student collection classes that support for each iteration cycles
Class Students implements Iterable {
// Store an array of all student classes
Private Student [] stus;
// This constructor can generate an array of student variables of the specified size and initialize the array of student variables
Public Students (int size ){
Stus = new Student [size];
For (int I = 0; I <size; I ++ ){
Stus [I] = new Student (String. valueOf (I), "Student" + String. valueOf (I ));
}
}
// An important method for implementing the Iterable interface, returning custom iteration variables
Public Iterator iterator (){
Return new StudentIterator ();
}
// Private internal class implementing the Iterator interface, which cannot be directly accessed from outside
Private class StudentIterator implements Iterator {
// Subscript of the current iteration element
Private int index = 0;
// Determine whether there is another element. If the last element is iterated, false is returned.
Public boolean hasNext (){
Return index! = Stus. length;
}
// Return the data of the current element and increment the subscript
Public Object next (){
Return stus [index ++];
}
// This operation is not supported. An operation exception is thrown.
Public void remove (){
Throw new UnsupportedOperationException ();
}
}
}
// Student
Class Student {
// Student ID
Private String sid;
// Student name
Private String name;
// Default constructor
Public Student (){
}
// Constructor supporting attribute value initialization
Public Student (String sid, String name ){
SetSid (sid );
SetName (name );
}
// Reading function of student ID
Public String getSid (){
Return sid;
}
// Student ID setting function
Public void setSid (String sid ){
This. sid = sid;
}
// Reading function of student name
Public String getName (){
Return name;
}
// Student name setting function
Public void setName (String name ){
This. name = name;
}
// Output formatted characters
Public String toString (){
Return this. sid + ":" + this. name;
}
}
Why must I implement the Iterable interface? Why not directly implement the Iterator interface?
Let's take a look at the collection classes in JDK, such as List or Set,
Both implement the Iterable interface, but do not directly implement the Iterator interface.
It makes sense to think about this. Because the core method of the Iterator interface is next () or hasNext ()
YesDependent on the current iteration position of the iterator.
If the Collection directly implements the Iterator interface, the Collection object will inevitably contain the data (pointer) at the current iteration position ).
When a set is transmitted between different methods, the result of the next () method becomes unpredictable because the current iteration position cannot be preset.
Unless you add a reset () method to the Iterator interface to reset the current iteration position.
But in this way, the Collection can only have one current iteration position at the same time.
Iterable does not. Each call will return an iterator counted from the beginning.
Multiple iterators do not interfere with each other
Iterator and iterable