PackageCn.aust.zyw.demo;ImportJava.util.Iterator;/*** Created by Zyw on 2016/2/16. * Iterator mode is the standard access method used to traverse the collection class. * It abstracts the access logic from different types of collection classes, thus avoiding exposing the internal structure of the collection to the client. * The store class inherits the Iterable interface, using the custom Hasnext (), Next () * to output the elements of array A. */ Public classtestiterable { Public Static voidMain (String args[]) {testiterable testiterable=Newtestiterable (); } testiterable () {Store store=NewStore (); System.out.println ("************"); for(String item:store) {System.out.print (item+" "); }//For (Iterator iter = Store.iterator (); Iter.hasnext ();) {//System.out.print (Iter.next () + "");// } }}classStoreImplementsIterable<string>{ PrivateString a[]={"Apple", "orange", "pear", "banana"}; @Override PublicIterator<string>iterator () {return NewIterator<string>() { Private intI=0; @Override Public BooleanHasnext () {//Returns True if the iteration have more elements if(i<a.length) { return true; } return false; } @Override PublicString Next () {//Returns the next element in the iteration. returna[i++]; } }; }}
Java iterator Demo