我可以编写一个嵌套循环来迭代嵌套数组的元素,for-each优雅地隐藏遍历嵌套数组的每个级别的遍历细节:
Foo[][] dbl_array;
public void do_all() {
// Iterate over both levels of a nested array, invoking "bar" on each inner element.
for (final Foo[] arr_1d : dbl_array) {
for (final Foo el : arr_1d) {
el.bar();
}
}
}
但这种方法的问题是:
所以...我如何更改这个以便实现一个我可以调用的Iterator:
Foo_Iterator fi = Foo.iterator();
for (final Foo el : fi) { // The Iterator hides the traversal details from the caller.
el.bar(); // The desired function is invoked on each element encountered.
}
这将留下如何对Foo_Iterator类进行迭代的细节。
我的问题是“如何编写Foo_Iterator,跟踪嵌套迭代器的状态? 我认为它看起来像下面这样,但我错过了跟踪状态的位。
class Foo_Iterator extends Whiz implements Iterator {
public Foo_Iterator() {
// Initialize state based on access to the superclass Whiz.
}
public boolean hasNext() {
// Is there an elegant way to save the state of both iterators between each call to hasNext() and next()?
// The "inelegant" way would be to keep track of the inner and out array indices,
// comparing the current index to the array length...
}
public Foo next() {
// Access the "next" in the nested sequence.
}
public void remove() {
// I probably won't implement or need/use this one.
}
}
关于如何以“优雅”方式做到这一点的任何建议?
感谢。