Chce utworzyć iterator, ale także ułatwić przebieg interwału, obsługując składanie foreach Java jak w ponizszym przykladzie.
for(int i:panel2(1,5))
System.out.println(i); // devuelve 1 2 3 4 5
Muszę zaimplementować Iterable, co wymaga wykonania metody iterator.
W tej chwili próbowałem:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Panel implements Iterable<Integer>{
int begin;
int end;
// alguna lógica acá para llenar los valores de begin y de end, como constructor y/o setter y getter.
public Panel(int begin, int end){
this.begin = begin;
this.end = end;
}
@Override
public Iterator<Integer> iterator() {
return panel1(begin,end);
}
private static Iterator<Integer> panel1(final int begin,final int end){
Iterator<Integer> it = new Iterator<Integer>(){
private int nextValue = begin;
private final int max = end;
public boolean hasNext() {
return nextValue <= max;
}
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return Integer.valueOf(nextValue++);
}
public void remove() {
throw new UnsupportedOperationException();
}
};
return it;
}
public static void main(String[] args) {
Panel panel = new Panel(1,5);
for(int i:panel)
System.out.println(i);
}
}
Ale to mnie zwraca:
C:\Users\antoi\Documents\Programming\Julien\TD7_iterators>java Panel.java
error: class found on application class path: Panel