Iterator is an iterator interface (Interface) in Java that is used to provide standard Java iterators
Iterator supports generics because the type that the collection (Collection) class can mount is indeterminate, and the object type is removed from the collection, and the generics are told that the compiler determines the type of object to mount, and that the value does not need to be cast.
For each is a new looping structure in Java 5, essentially a iterator, characterized by the ability to traverse collection elements without regard to the set subscript.
Comprehensive Example:
Packagenet.csdn.shf4715;ImportJava.util.ArrayList;ImportJava.util.Iterator;ImportJava.util.List; Public class iteratordemo {A comprehensive example of/** * iterator and for each * @param args */ Public Static void Main(string[] args) {//Create a list and set the generic to EMP typelist<emp> list =NewArraylist<emp> ();//Add an EMP instance to the listList.add (NewEMP ("One")); List.add (NewEMP ("*")); List.add (NewEMP ("both")); List.add (NewEMP ("*")); List.add (NewEMP ("three")); List.add (NewEMP ("*"));//Use the iterator () method of list to return an iteratorIterator<emp> it = List.iterator ();//hasnext () a method in iterator to determine if there is a next element while(It.hasnext ()) {//If the value of name in the EMP object is * then delete the element if("*". Equals (It.next (). GetName ())) {it.remove (); }} System.out.println (list);//enhanced for loop for iterating over the collection, but not for deleting the collection //But can be modified for(Emp e:list) {List.set (1,NewEMP ("1")); System.out.print (E.getname () +" "); } }}/** * EMP class * @author Haydn * */Class Emp {PrivateString name; Public EMP(String name) {Super(); This. name = name; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringtoString() {returnName }}
Operation Result:
[One, both, three]
One 1 Three
The difference between iterator and for:
1.for each cannot delete a collection element
2.Iterator can only use its own remove () method to delete an element and cannot use the delete operation of the collection
3.ArrayList, for loop faster, LinkedList, use iterator faster
Summary: The two traversal methods have their own characteristics, the advantages are different, in dealing with different scenarios of data, the use of their strengths can make the program run better.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java iterator and enhanced for loop for each detailed