集册 Java实例教程 实现迭代器接口

实现迭代器接口

欢马劈雪     最近更新时间:2020-01-02 10:19:05

558
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
实现迭代器接口

public class DataStructure {


    // Create an array

    private final static int SIZE = 15;/** 来 自 时 代 J a v a - N o w J a v a . c o m**/

    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

        DataStructureIterator iterator = this.new EvenIterator();
        /** 
         来自 时 代 J a v a 公 众 号 - nowjava.com**/

        while (iterator.hasNext()) {

            System.out.print(iterator.next() + " ");

        }

        System.out.println();

    }


    interface DataStructureIterator extends java.util.Iterator<Integer> {

    }


    // Inner class implements the DataStructureIterator interface,

    // which extends the Iterator<Integer> interface


    private class EvenIterator implements DataStructureIterator {


        // Start stepping through the array from the beginning

        private int nextIndex = 0;


        public boolean hasNext() {


            // Check if the current element is the last in the array

            return (nextIndex <= SIZE - 1);

        }


        public Integer next() {


            // Record a value of an even index of the array

            Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);


            // Get the next even element

            nextIndex += 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();

    }

}


展开阅读全文