One, for,for each and iterator usage and difference:
Same point: Three can be used to iterate over arrays and collections
Different points:
1. Form Difference
// the for is in the form for (int i=0; i<arr.size (); i++) {...} // the form of foreach is for (int i:arr) {...} // the form of iterator is Iterator it = arr.iterator (); while (It.hasnext ()) { object o =it.next (); ...}
2. Condition difference:
For needs to know the size of the collection or array, and needs to be ordered, otherwise it cannot traverse;
Both foreach and iterator do not need to know the size of the collection or array, and they all get each element within the set and then process it;
3, polymorphic differences:
Both for and foreach need to know the type of the collection, even the type of elements within the collection, that is, access to the internal members, not the implementation of the State;
Iterator is an interface type that doesn't care about the type of collection or array, and he can modify and delete the elements of a collection at any time, for example:
Public void Display (iterator<object> it) { while(It.hasnext ()) { System. out. Print (It.next () +"");} }
When we need to traverse different sets, we only need to pass the collection of iterator (such as Arr.iterator ()) to understand, this is the benefit of iterator, he does not contain any information about the sequence he traversed, the operation of the traversal sequence and the underlying structure of the sequence can be separated. Iterators unify the way the container is accessed, which is the best embodiment of the decoupling of the interface.
4. Usage Difference
A For loop is typically used to handle relatively simple, ordered, predictable-sized collections or arrays
foreach can be used to iterate through any collection or array, and the only downside is that he needs to understand the type of the collection's internal
Iterator is the most powerful, he can modify or delete the elements inside the collection at any time, and it is done without needing to know the types of elements and collections (reason can refer to the 3rd: polymorphic difference), when you need to implement the same traversal method for different containers, the iterator is the best choice!
Java Traversal Summary: