First, the iterator API
There are three main methods for iterator: Hasnext (), Next (), remove ()
hasnext: No pointer down action, just to determine if the next element exists next
: The pointer moves down and returns the element
to which the pointer points Remove: Deletes the element to which the current pointer is pointing, usually with the next method, by removing the element returned by the next method
Second, the principle of the iterator
1. When creating a iterator object that points to a collection or container, this pointer actually points to the top of the first element, that is, to an empty
2, and when the Hasnext method is called, it simply determines whether the next element is there or not, and does not move the pointer
3, When the next method is called, the pointer is moved down, and the element pointed to by the pointer is returned, and if there is no element in the memory pointed to by the pointer, it is reported to be abnormal .
4. The Remove method removes the element that the pointer points to. An exception is thrown if there are no elements in the memory that the current pointer points to.
Third, the use of iterators
Iterators are typically used to iterate over a collection.
Iv. issues of attention in use
The iterator in Java is a fail-fast design.
when iterator iterates over a container, if there is another way to change the contents of the collection (container) at this time, then iterator throws
Concurrentmodificationexception. As the official document repeatedly emphasizes: Thus, in the face of
concurrent modification, the iterator fails quickly and cleanly, rather than Riskin G arbitrary, non-deterministic behavior at a undetermined time in the future
.
In order to avoid this exception, the solution that can be taken is:
1. If the current single thread is changing the container (add, delete ...), then using the Iterator.remove () method during the iteration ensures that the pointer is not lost while the iterator is looking for next.
while (Iterator.hasnext () {
Object item = Iterator.next ();
Iterator.remove (); important! Avoid concurrentmodificationexception ...
}
2. If more than one thread is currently operating on a container, such as when one thread is writing data to the container, and another thread is iterating over the container, then it must consider thread safety issues in concurrency. The first sentence of the official Concurrentmodificationexception document states:
This exception are thrown by methods that has detected concurrent modification of an object when such modification is Not permissible.
This exception can be resolved by using a thread-safe container under the Java.util.concurrent package.
Finally, concurrentmodificationexception should always be used to solve a bug, not to check the correctness of the program (Try...catch ...).