我是Java新手,下面的代码来自Java教程Oracle。
我对的两个问题感到困惑
1) 有人能告诉我在的上下文中"this"关键字指的是什么吗
DataStructureIterator iterator = this.new EvenIterator();
我已经从声明中删除了"this"关键字,一切似乎都很好。"this"关键字是否提供了一些我不知道的特殊功能,或者它是多余的?
2) 有什么用
interface DataStructureIterator extends java.util.Iterator<Integer> { }
真的有必要吗?因为我已经从代码中删除了它(以及一些小的相关更改),一切都很好。
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();
}
}
DataStructureIterator
在不添加任何新方法的情况下扩展了java.util.Iterator<Integer>
。因此,任何使用它的地方都可以安全地用java.util.Iterator<Integer>
代替。
this.new EvenIterator()
中的this
指的是当前DataStructure
实例,该实例用作该语句中正在实例化的内部EvenIterator
类的实例的封闭实例。由于您是从封闭类DataStructure
的实例中创建EvenIterator
的实例,因此无需显式指定它,并且new EvenIterator()
可以工作。