我不明白这一行:
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();
}
}
答案 0 :(得分:1)
是的,你是对的;在大多数情况下,您可以取消DataStructureIterator
并直接使用Iterator<Integer>
。
像这样定义DataStructureIterator
会为Iterator<Integer>
创建速记符号,但它是非常差的速记。例如,它根本不像C中的typedef。
您可以将实现DataStructureIterator
的任何对象分配给Iterator<Integer>
,但不能将实现Iterator<Integer>
的所有对象分配给DataStructureIterator
。
所以,虽然定义一个像这样的空接口是合法的,但没有太多意义。它可能导致混乱。