我目前正在学习Java,对于我的内部课程练习,我打了下面的代码:
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 void setNextIndex(int i){
nextIndex=i;
}
}
public void print(DataStructureIterator iterator) {
// Print out values of odd indices of the array
//iterator = this.new EvenIterator();
iterator.setNextIndex(1);//**This line giving me compiler error that setNextIndex is undefined for type DataStructure.DataStructureIterator **
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
}
public EvenIterator createNewObject(){
return this.new EvenIterator();
}
public static void main(String s[]) {
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
System.out.println("Even Index");
ds.printEven();
System.out.println("Odd Index");
ds.print(ds.createNewObject());
}
}
我将EvenIterator对象传递给方法print(DataStructureIterator),据我所知,迭代器可以引用EvenIterator对象(因为DataStructureIterator是由EvenIterator实现的),尽管hasNext()和setNextIndex(int)是在同一个类中,引用迭代器只能访问hasNext。
如何修复此错误?
答案 0 :(得分:0)
print
方法知道其参数为DataStructureIterator
。是否在该接口中声明了方法setNextIndex
?如果没有,您必须添加它。
答案 1 :(得分:0)
即使您将EvenIterator
传递给方法print(DataStructureIterator)
,它也会默默地投放到DataStructureIterator
。因此,如果未在setNextIndex(int)
中声明DataStructureIterator
方法,您将无法访问它。