【发布时间】:2013-04-03 15:11:16
【问题描述】:
我有一个如下形式的 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; }
}
我希望能够使用这样的迭代器从外部迭代私有数据:
for(byte b : Example) { ;/* do stuff */ }
我尝试实现一个私有 Iterator 类,但遇到了问题:
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
}
如何为原始类型(不是泛型)实现 external 迭代器?这在 Java 中可行吗?
【问题讨论】:
标签: java iterator primitive private-members autoboxing