To implement a class that can be used with a foreach loop, you must implement Iterable, which overrides a Iterator method, which returns a iterator<e> interface.
The code is as follows:
public class Itertest implements Iterable<string> {
Stores the contents of the array private object[] Obj=new object[1];//record the number of elements added to the private int size;
Records the current element's subscript private int current=0;//add element public void Add (String str) {
Determine if the array is full if it is full of expanded array if (size==obj.length) {//expanded array to a new length obj=arrays.copyof (obj, obj.length+obj.length<<1);} Obj[size++]=str;}
Overriding the Iterator method public iterator<string> Iterator () {defines inner classes that implement the Iterator class "ITER implements Iterator<string >{@Overridepublic Boolean Hasnext () {//Determines whether the current pointer is less than the actual size if (current<size) {return true;} return false;} @Overridepublic String Next () {//returns the current element and moves the current subscript forward to return obj[current++].tostring ();} @Overridepublic void Remove () {//TODO auto-generated Method stub}}//Returns the custom Iteraror subclass return new ITER ();}}
In Java, you implement a class that can use the Foreach Loop iterable,iterator