iterator是java迭代器最简单的实现。
public interface iterator { boolean hasnext(); object next(); void remove(); }
2.iterator中的常用方法
(1)e next():返回迭代中的下一个元素
(2)boolean hasnext():如果迭代具有更多元素,则返回true
3.iterator迭代实例
public class iteratordemo {public static void main(string[] args) {collection<string> coll = new arraylist<string>(); //多态coll.add(abc1);coll.add(abc2);coll.add(abc3);coll.add(abc4);// 迭代器,对集合arraylist中的元素进行取出// 调用集合的方法iterator()获取iterator接口的实现类的对象iterator<string> it = coll.iterator();// 接口实现类对象,调用方法hasnext()判断集合中是否有元素// boolean b = it.hasnext();// system.out.println(b);// 接口的实现类对象,调用方法next()取出集合中的元素// string s = it.next();// system.out.println(s); // 迭代是反复内容,使用循环实现,循环的终止条件:集合中没元素, hasnext()返回了falsewhile (it.hasnext()) {string s = it.next();system.out.println(s);}}}
以上就是java迭代器iterator怎么定义的详细内容。
