我有一个如下形式的 Java 类:
class Example {
private byte[][] data;
public Example(int s) { data = new byte[s][s]; }
public byte getter(int x, int y) { return byte[x][y]; }
public void setter(int x, int y, byte z) { byte[x][y] = z; }
}
我希望能够像这样使用迭代器在外部迭代私有(private)数据:
for(byte b : Example) { ;/* 做一些事情 */}
我试图实现一个私有(private)迭代器类,但我遇到了问题:
private class ExampleIterator implements Iterator {
private int curr_x;
private int curr_y;
public ExampleIterator() { curr_x=0; curr_y=-1; }
public boolean hasNext() {
return curr_x != field.length-1
&& curr_y != field.length-1; //is not the last cell?
}
public byte next() { // <-- Error is here:
// Wants to change return type to Object
// Won't compile!
if(curr_y=field.length) { ++curr_x; curr_y=0; }
return field[curr_x][curr_y];
}
public void remove() { ; } //does nothing
}
我如何为基本类型(不是泛型)实现一个外部迭代器?这在 Java 中可行吗?
最佳答案
迭代器不能产生原始类型的值。但是,它可能会产生包装器类型的值 Byte
.这些值可以是 auto-unboxed放入 byte
(只要它们不是 null
)。
private class ExampleIterator implements Iterator<Byte> {
public boolean hasNext() { ... }
public Byte next() { ... }
}
然后你可以像这样使用它:
for (byte b : example) { ... }
关于原始类型的 Java 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15791210/