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

How to define java iterator iterator

WBOY
Release: 2023-05-03 20:13:05
forward
1085 people have browsed it

1.interator interface definition

Iterator is the simplest implementation of Java iterator.

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

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);
}
}
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template