Ich habe eine Java-Klasse in der folgenden Form:Java Iterator für primitive Typen
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; }
}
Ich mag würde extern können, über die privaten Daten iterieren mit einem Iterator wie so:
for(byte b : Example) { ;/* do stuff */ }
ich habe versucht, eine private Iterator-Klasse zu implementieren, aber ich lief in Probleme:
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
}
Wie würde ich einen externen Iterator für primitive Typen (nicht Generika) implementieren? Ist das in Java möglich?
Gibt es für primitive Typen ein analoges 'Iterable', also kann ich' for (double d: myContainerWithDoubles) {} '? –
Es gibt keinen for-each primitiven Iterator. Die beste Übereinstimmung besteht darin, 'PrimitiveIterator.OfDouble' zu implementieren und auf funktionale Weise zu verwenden. – Oroboros102