我是 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
在this.new EvenIterator()
指当前DataStructure
用作内部实例 EvenIterator
的封闭实例的实例该语句中正在实例化的类。由于您正在创建 EvenIterator
的实例来自封闭类的实例 DataStructure
,无需明确指定,并且 new EvenIterator()
有效。
关于java - 'this' 关键字在 DataStructureIterator iterator = this.new EvenIterator(); 的上下文中指的是什么;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34611392/