Home >Java >javaTutorial >How to define java iterator iterator

How to define java iterator iterator

WBOY
WBOYforward
2023-05-03 20:13:051046browse

1.interator interface definition

Iterator is the simplest implementation of Java iterator.

public interface Iterator {  
  boolean hasNext();  
  Object next();  
  void remove();  
}

2. Commonly used methods in Iterator

(1)E next(): Returns the next element in the iteration

(2)boolean hasNext(): Returns true if the iteration has more elements

3.Iterator iteration instance

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()返回了false
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}

The above is the detailed content of How to define java iterator iterator. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete