为什么要写这样的迭代器呢?

May*_*May 1 java

我正在阅读关于内部类的Java教程

http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

它解释了在示例"InnerEvenIterator内部类,它类似于标准的Java迭代器".所以我认为迭代器在Java中很常见?

我来自C编程背景.我不明白为什么这样的简单循环

for(i=0;i <SIZE;i+2){
System.System.out.println(arrayOfInts[i]));
}
Run Code Online (Sandbox Code Playgroud)

用两种方法扩展到迭代器(内部类).这有什么意义?

public class DataStructure {
    //create an array
    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        //fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }

    public void printEven() {
        //print out values of even indices of the array
        InnerEvenIterator iterator = this.new InnerEvenIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.getNext() + " ");
        }
    }

//inner class implements the Iterator pattern
    private class InnerEvenIterator {
        //start stepping through the array from the beginning
        private int next = 0;

        public boolean hasNext() {
            //check if a current element is the last in the array
            return (next <= SIZE - 1);
        }

        public int getNext() {
            //record a value of an even index of the array
            int retValue = arrayOfInts[next];
            //get the next even element
            next += 2;
            return retValue;
        }
    }

    public static void main(String s[]) {
        //fill the array with integer values and print out only values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 6

对于数组上的简单循环,您(通常)不会在Java中使用Iterator.

for(int i=0;i < arrayOfInts.length ; i+2){
     System.out.println(arrayOfInts[i]));
}
Run Code Online (Sandbox Code Playgroud)

迭代器的想法是解耦数据从其使用者(想要迭代它的代码)的存储方式(可能不是数组).

你说Iterator在Java类库中是一个非常核心的概念是正确的,因此从Java5开始就是通用的for-each循环语言功能来支持它.通过此循环,用户甚至不再看到Iterator.

for(Something element: listOfSomething){
    System.out.println(element);
}
Run Code Online (Sandbox Code Playgroud)

如果我要实现一个"偶数步进迭代器",我会将它建立在普通的迭代器上,这样它就可以用于任何类型的迭代.

public class EvenSteppingIterator<X> implements Iterator<X>{

      private final Iterator<X> source;

      public EvenSteppingIterator(Iterator<X> source){
          this.source = source;
          // skip the first one, start from the second
          if (source.hasNext()) source.next();
      }

      public boolean hasNext() {
          return source.hasNext();
      }

      public X next(){
          X n = source.next();
          // skip the next one
          if (source.hasNext()) source.next();
          return n;
      }


}
Run Code Online (Sandbox Code Playgroud)