Home  >  Article  >  Java  >  General usage of Iterator in Java learning

General usage of Iterator in Java learning

高洛峰
高洛峰Original
2016-12-13 17:05:161348browse

Iterator (Iterator)

  Iterator is a design pattern. It is an object that can traverse and select objects in a sequence without the developer needing to understand the underlying structure of the sequence. Iterators are often called "lightweight" objects because they are cheap to create.

 The Iterator function in Java is relatively simple and can only move in one direction:

 (1) Use the method iterator() to ask the container to return an Iterator. The first time the Iterator's next() method is called, it returns the first element of the sequence. Note: the iterator() method is the java.lang.Iterable interface and is inherited by Collection.

 (2) Use next() to get the next element in the sequence.

 (3) Use hasNext() to check whether there are still elements in the sequence.

  (4) Use remove() to delete the element newly returned by the iterator.

 Iterator is the simplest implementation of Java iterator. ListIterator designed for List has more functions. It can traverse List in two directions, and can also insert and delete elements from List.

Iterator application:
list l = new ArrayList();
l.add("aa");
l.add("bb");
l.add("cc");
for (Iterator iter = l.iterator(); iter.hasNext();) {
String str = (String)iter.next();
System.out.println(str);
}
/*Iterator is used in while loop
Iterator iter = l.iterator();
while(iter.hasNext()){
String str = (String) iter.next();
System.out.println(str);
}
*/


Statement:
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
Previous article:Android custom ListViewNext article:Android custom ListView