Iterator (use of iterator)

Iterator

  An iterator is a design pattern, it is an object that can traverse and select objects in a sequence without the developer needing to know 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) Using the method iterator() requires 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, which is inherited by Collection.

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

  (3) Use hasNext() to check if there are more elements in the sequence.

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

  Iterator is the simplest implementation of Java iterator. The ListIterator designed for List has more functions. It can traverse the List from two directions, and can also insert and delete elements from the 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);
 }
 /*迭代器用于while循环
 Iterator iter = l.iterator();
 while(iter.hasNext()){
     String str = (String) iter.next();
     System.out.println(str);
 }
 */

Interface definition of Iterator:

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

Use: Object next(): Returns a reference to the element just passed by the iterator, the return value is Object, which needs to be cast to the type you need

    boolean hasNext(): Determines whether there are any more accessible elements in the container

    void remove(): removes the element just passed by the iterator

Iterative usage method: (Iteration can be simply understood as traversal, which is a method class for standardizing traversal of all objects in various containers)

for(Iterator it = c.iterator(); it.hasNext(); ) {  
  Object o = it.next();  
   //do something  
}  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325341651&siteId=291194637