A series of important set classes are included in the Java.util package. This article will start from the analysis source code, and in depth, the internal structure of a collection class, and the source code that traverses the collection iterative mode implementation inside. Let's first discuss a root-interface Collection and then analyze an abstract class AbstractList and its corresponding Iterator interface, and carefully study the realization of the iterative score. The source code version discussed herein is JDK 1.4.2, because JDK 1.5 uses a lot of generic code in Java.util, in order to simplify the problem, so we still discuss the code of the 1.4 version. The root of the collective class Collection Collection interface is the root type of all collection classes. Its main interface method is: Boolean Add (Object C) add () method will add a new element. Note that this method returns a boolean, but the return value is not indicating that the success is or not. Read DOC carefully, Collection stipulates: If a collection refuses to add this element, no matter what reason, you must throw an exception. The meaning of this return value is that after the add () method is executed, the collection content changes (that is, there is no number of elements, the location, etc.), which is implemented by the specific class. That is: If the method is wrong, the abnormality will always be thrown; the return value only indicates that this Collection content is changed after the method is executed. Similar to: Boolean ADDALL (Collection C); Boolean Remove (Object O); Boolean Removeall (Collection C); Object [] toArray () method is very simple, convert the collection into array returns. Object [] toArray (Object [] a) method is a bit complicated. First, the return of Object [] is still the array of all elements of the collection, but the type and parameter A type is the same, such as execution: string: string: string [] o = (String []) C.Toarray (New String [0]); the obtained O actual type is String []. Secondly, if the parameter A is largely installed, the return will be a new array. If the size of the parameter A can install all elements of the collection, the return is still A, but the contents of A are filled with a collection element. It is especially noted that if the size of A is more than the number of set elements, the portion behind the A is set to NULL. The last most important method is Iterator (), returns an Iterator, used to traverse all elements of the collection. Implementing traversal set Iterator mode is a standard access method for traversing a collection class. It can abstract access logic from different types of set classes to avoid exposing the internal structure of the collection to the client. For example, if you don't use iTerator, the method of traversing an array is to use an index: for (int i = 0; i More terror is that if you need to replace ArrayList to LinkedList, the original client code must be overwritten. To solve the above problems, the Iterator mode always uses the same logic to traverse the collection: for (item it = c.iterage (); it.hasnext ();) {...} The mystery is that the client itself does not maintain traversal collection "Pointer", all internal states (such as the current element location, whether the next element) is maintained by Iterator, and this Iterator is generated by the set class by the factory method, so it knows how to traverse the entire collection. The client is derived from not directly and the collection class. It always controls the command to send "forward", "back", "rear", "Take the current element" command, can be traversed throughout the collection. First look at the definition of the Java.util.Iterator interface: public interface itrator {boolean hasnext (); Object next (); void transove ();} Depending on the first two methods can complete traversal, typical code as follows: for (Iterator IT = C.iterator (); it.hasnext ();) {Object O = it.next (); // The operation of O O'Ds ...} In JDK1.5, the above code is in grammar Simplified: // Type is a specific type, such as String. For (Type T: c) {// Type T's Operation ...} The specific type of Iterator's specific type returned by each set class may return ArrayIterator, and the SET may return setiterator. Tree may return TreeITerator, but they all implement The Iterator interface, therefore, the client doesn't care which Iterator, it only needs to get this Iterator interface, this is the object-oriented power. Iterator Source Patients Let's take a look at how AbstractRacylist creates Iterator. First ABSTRACTLIST defines an internal class: Private class itr imports iterator {...} and the definition of the iTerator () method is: public iterator itrator () {return new itr ();} So the client doesn't know it Through Iterator IT = a.iterator (); the true type of Iterator obtained. Now we care about how this is the ITR class of Private is how to traverse AbstractList: private class itr imports itrator {int cursor = 0; int LastRet = -1; int expectedmodcount = modcount;} ITR class relies on 3 int variables ( There is also a reference for implied AbstractList to implement traversal. Cursor is the next time next time Next () call time element, the first call next () will return an element of index 0. Lastret records the last cursor, so it is always less than Cursor. Variables Cursor and collection of elements of the elements of the collections determine HASNext (): public boolean Hasnext () {return curSor! = Size ();} method NEXT () Returns the element of the index for cursor, then modify the value 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 represented expected modCount Value, used to determine whether the collection is modified during the traversal process. AbstractList contains a Modcount variable, which is 0, and modcount plus 1 when the collections are modified once (call add, remove, etc.). Therefore, if MODCOUNT is not changed, the collection content is not modified. Itr initialization recording modCount set of variables with expectedModCount, thereafter, where necessary, it checks the value of modCount: final void checkForComodification (); if modCount with a start recording {if throw new ConcurrentModificationException () (modCount = expectedModCount!)} The value in the expectedmodecount is not equal, indicating that the collection content is modified, and the ConcurrentModificationException will be thrown. This ConcurrentModificationException is RuntimeException, do not capture it on the client. If this exception occurs, there is a problem with the writing of program code, and you should check the code carefully instead of ignore it in catch. However, the Remove () method called Iterator itself is completely no problem, because the value of ExpectedModcount and Modcount is automatically synchronized in this method: public void remove () {... AbstractList.This.Remove (Lastret); ... // Reset the expectedmodcount: expectedmodcount = modcount; ...} to ensure that the traversal process is successfully completed, it must ensure that the collection is not changed during traversal (Remove of Iterator) Except of the method), so ensure that the trail of traids is to use this collection only in one thread, or synchronize the traversal code in the multi-thread. Finally, give a complete example: 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 change the ArrayList of the first line of code to LinkedList or Vector, you can compile if the rest of the code doesn't have to change the line. And the function is constant, this is the principle of abstract programming: the degree of dependence on the specific class is the smallest. Author blog: http://blog.9cbs.net/chensheng913/