I was getting out of memory exceptions when I stored a collection of my class AbstractState in memory, so I am trying to write an iterable/iterator. I have a bit of C# knowledge but little Java experience. In C# I would write a method returning an IEnumerable<AbstractState>, but it doesn't seem so easy here.
AbstractState stores a pair of coordinates, although depending on the implementation, the operations on them differ. (It also extends a generic MyPair<Coordinate>.)
Within AbstractState, I define a constructor AbstractState(Coordinate A, Coordinate B){super(A,B);}. I override this in some but not all sub-classes. Coordinate is concrete. Here is my iterable:
import java.util.Iterator;
public class StateSpace<T extends AbstractState> implements Iterable<T> {
@Override
public Iterator<T> iterator() {
return new StateIterator();
}
}
and my Iterator:
public class StateIterator<T extends AbstractState> implements Iterator<T> {
private Iterator<Coordinate> iX, iY;
StateIterator(){
iX = Main.GRID.iterator();
iY = Main.GRID.iterator();
}
@Override
public boolean hasNext() {
return iX.hasNext() || iY.hasNext();
}
@Override
public T next() {
return null;
}
}
(GRID here is a static range of Coordinates.)
How can I implement the next() method correctly? (Or, what is a better design for my code to solve this problem?)
Instantiating a T does not work, and I cannot instantiate an abstract class. I think I was close by trying
getDeclaredConstructor(Coordinate.class, Coordinate.class).newInstance(iX.next(), iY.next());
but I got a compiler warning for no such method.
I had unchecked casts when I casted to a T, so suspect that this is a bad idea. Having many iterators/iterables is unappealing, as I would be checking (via if statements or a switch) which iterator I need, which undermines my OO code design.
Any suggestions appreciated, thanks