Java's Iterator interface (iterators)

Iterator Interface Overview

Program development, often need to traverse all elements in the collection. In response to this demand, JDK specializes in providing an interface java.util.Iterator. Iterator interface is a set of Java, but it is the Collection, Map interfaces are different, Map Collection interfaces and interface is mainly used for storage elements, while Iterator mainly used to iterate (ie, traverse) elements in the Collection, so Iterator the object is also known as iterators.

The concept iteration

Iteration : the General Collection Obtaining a collection of elements. Before taking the element must first set has no elements is determined, if there is, to put the element taken out, continue to determine if there would no longer taken up. It has all the elements in the collection all out. This embodiment taken jargon called iteration.

Gets an iterator

Iterator iterator is an interface, we can not directly use, need to realize the class object Iterator interface, access implementation class way of special Collection interface has a method called iterator (), this method returns iterators to achieve class object iterator <E> iterator () returns an iterator in the elements of this collection.

  • public Iterator iterator (): Get set corresponding iterator to iterate over the elements of the collection.

Iterator interface common method as follows:

  • public E next (): Returns the next element of the iteration
  • public boolean hasNext (): if the iteration has more elements, it returns true.

The step of using the iterator

  1. Use iterator set () Gets the iterator class object implemented using Iterator interface receiver (polymorphism)
  2. Use hasNext Iterator interface element is determined there is no next
  3. Iterator using interface method next fetches the next element in the set

Code Example

Package demo02; 

Import of java.util.ArrayList;
 Import java.util.Collection;
 Import the java.util.Iterator; 

public  class Demo01Iterator {
     public  static  void main (String [] args) {
         // create a collection object 
        Collection <Integer> coll = new new the ArrayList <> ();
         // add to the elements in the set automatic packing 
        coll.add (. 1 ); 
        coll.add ( 2 ); 
        coll.add ( . 3 ); 
        coll.add ( . 4 );
         / *
            1. Use iterator set () Gets iterator class object implemented using Iterator interface receiver (polymorphism) 
            Note: 
                Iterator <E> is also generic interfaces, along with a set of generic iterator away, is set What is generic, what is the generic iterator 
         * / 
        // polymorphic class object interface 
        iterator <Integer> = IT coll.iterator ();
         // 2. use hasNext iterator interface element is determined there is no next 
        the while (it.hasNext ()) {
             // 3. the method of using the Iterator interface next fetches the next element in the set 
            System.out.println (it.next ()); 
        } 
    } 
}

The result of code execution

tips: During the collection element removed, if the set has no elements, and continue to use the iterator's next method, error java.util.NoSuchElementException no elements will occur.

The principle iterator

When traversing a collection, first obtained by calling Collection set iterator () method iterator object, and then use hashNext () method determines whether there is a next element in the set, if present, is invoked next () method of the element removed, otherwise described has reached the end of the collection, stop through the elements. Iterator iterator object in the loop through the collection, the internal pointer way to track the elements in the collection , in order to allow beginners to better understand how the iterator, followed by demonstration Iterator object elements by a legend:

 

Iterator before calling the next method, the iterator's index, before the first element, does not point to any element, when the first call to the next method iterator, the iterator's index will move back one, pointing to the first elements and returns that element, when the call to the next method again, the iterator's index will point to the second element and the element returns, and so on, until hasNext method returns false, indicating that reached the end of the collection, termination of traversing elements.

Enhancements for 

Enhanced for loop (also called for each cycle) is JDK1.5 came out of the loop for a high-level, designed to loop through the array and collections. Its interior is actually a principle Iterator iterator, so the process of traversal, can not add or delete elements of the collection operation. Why collections and arrays can be used to enhance a for loop to traverse? Because real now as long as the realization of the Iterable <T> interfaces allows objects to be "foreach" objective statement. The Collection <E> extends Iterable <E > this interface, so all the separate collection can be used to enhance for.
effect:
  • It is used to traverse the Collection and arrays. Usually carried out only through the elements, additions and deletions do not operate on a set of elements in the process of traversal.

format:

Code Example

Iterate

package demo02Iterator;

public class ForArray {
    public static void main(String[] args) {
        int[] arr = {3, 5, 6, 87};
        //使用增强for遍历数组
        for (int a : arr) {//a代表数组中的每个元素
            System.out.print(a + " ");//3 5 6 87
        }
    }
}

遍历集合

package demo02Iterator;

import java.util.ArrayList;
import java.util.Collection;

public class ForArrayList {

    public static void main(String[] args) {
        //遍历集合
        Collection<String> coll = new ArrayList<String>();
        coll.add("小河神");
        coll.add("老河神");
        coll.add("神婆");
        //使用增强for遍历
        for (String s : coll) {
            //接收变量s代表 代表被遍历到的集合元
            System.out.print(s + " ");//小河神 老河神 神婆 
        }
    }
}

 

 

Guess you like

Origin www.cnblogs.com/wurengen/p/12012065.html