Oracle内部类示例

时间:2015-06-06 02:28:28

标签: java inner-classes

我不明白这一行:

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

因为DataStructeIterator和迭代器之间没有区别,我们只能删除这一行,而是说:

private class EvenIterator implements java.util.iterator<Integer> { //code goes here}

我错过了什么?

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
        DataStructureIterator iterator = this.new EvenIterator();
        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();
    }
}

1 个答案:

答案 0 :(得分:1)

是的,你是对的;在大多数情况下,您可以取消DataStructureIterator并直接使用Iterator<Integer>

像这样定义DataStructureIterator会为Iterator<Integer>创建速记符号,但它是非常差的速记。例如,它根本不像C中的typedef。

您可以将实现DataStructureIterator的任何对象分配给Iterator<Integer>,但不能将实现Iterator<Integer>的所有对象分配给DataStructureIterator

所以,虽然定义一个像这样的空接口是合法的,但没有太多意义。它可能导致混乱。