将迭代器维护为类的实例变量是非常不寻常的。您只能遍历一次数组-
可能不是您想要的。您更可能希望您的类为要遍历数组的任何人提供一个迭代器。下面是一个更传统的迭代器。
Java 5+代码-我没有尝试编译或运行,因此可能包含错误(当前不在开发机器附近)。它还使用自动装箱转换
Integer为
int。
public class MyArray implements Iterable<Integer> { public static class MyIterator implements Iterator<Integer> { private final MyArray myArray; private int current; MyIterator(MyArray myArray) { this.myArray = myArray; this.current = myArray.start; } @Override public boolean hasNext() { return current < myArray.end; } @Override public Integer next() { if (! hasNext()) throw new NoSuchElementException(); return myArray.arr[current++]; } @Override public void remove() { // Choose exception or implementation: throw new OperationNotSupportedException(); // or //// if (! hasNext()) throw new NoSuchElementException(); //// if (currrent + 1 < myArray.end) { //// System.arraycopy(myArray.arr, current+1, myArray.arr, current, myArray.end - current-1); //// } //// myArray.end--; } } .... // Most of the rest of MyArray is the same except adding a new iterator method .... public Iterator<Integer> iterator() { return new MyIterator(); } // The rest of MyArray is the same ....}另请注意:请注意不要超过静态数组的500个元素限制。如果可以,请考虑使用ArrayList类。



