废话不多说,直接上代码:
package Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MyTest {
public static class MyIterable implements Iterable<String>{
private List<String> mylist;
public MyIterable(){
super();
mylist = new ArrayList<>();
}
public void Add(String value) {
mylist.add(value);
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
int myIndex = -1;
@Override
public boolean hasNext() {
return mylist.size()-1>myIndex;
}
@Override
public String next() {
myIndex++;
return mylist.get(myIndex);
}
};
}
}
public static void main(String[] args) {
MyIterable myIterable = new MyIterable();
myIterable.Add("111");
myIterable.Add("1122");
myIterable.Add("33");
Iterator<String> iterator = myIterable.iterator();
System.out.println(iterator.next());
Iterator<String> iterator2 = myIterable.iterator();
System.out.println(iterator2.next());
}
}