I am working on a school assignment in java and i have come across an error i can’t find an answer on.
Somehow, when i call the gethit() method on an object returned by iterator.next() i get a stack overflow exception.
I suspect because the gethit() method (in this specific case) calls on itself recursively. Even though, i think it is strange to get a stack overflow since the recursion only goes 2 or 3 levels deep and my objects don’t use an excessive amount of memory.
The shoot() method that makes the first call of gethit()
public void shoot() {
assert canHaveAsEnergy(energy - 1000);
//Search the target position.
Position laserPos = new Position(getPos().getX(), getPos().getY(), getPos().getBoard());
do {
long nextX = laserPos.getX() + new Double(orientation.getDirection().getX()).longValue();
long nextY = laserPos.getY() + new Double(orientation.getDirection().getY()).longValue();
laserPos.setX(nextX);
laserPos.setY(nextY);
} while (getPos().getBoard().canHaveAsPosition(laserPos) && (! getPos().getBoard().hasAsPosition(laserPos)));
//Hit every entity on the target position.
for (Entity entity : getPos().getBoard().getAllEntitiesOn(laserPos)) {
entity.getHit();
}
setEnergy(energy - 1000);
}
The getHit() method that recursively calls on itself.
public void getHit() {
ArrayList<Position> neighbours = new ArrayList<Position>();
Position northPos = new Position(getPos().getX(), getPos().getY() - 1, getPos().getBoard());
Position eastPos = new Position(getPos().getX() + 1, getPos().getY(), getPos().getBoard());
Position southPos = new Position(getPos().getX(), getPos().getY() + 1, getPos().getBoard());
Position westPos = new Position(getPos().getX() - 1, getPos().getY(), getPos().getBoard());
neighbours.add(northPos);
neighbours.add(eastPos);
neighbours.add(southPos);
neighbours.add(westPos);
for (Position pos : neighbours) {
if (getPos().getBoard().hasAsPosition(pos)) {
Iterator<Entity> iterator = getPos().getBoard().getAllEntitiesOn(pos).iterator();
while (iterator.hasNext()) {
//Somehow this gives a stack overflow error
iterator.next().getHit();
}
}
}
System.out.println(this.toString() + " takes a hit and explodes.");
getPos().getBoard().removeAsEntity(this);
terminate();
}
Everytime you call iterator, that will call another iterator that will call another iterator, and so forth. Thus your stack overflow from infinite recursion due to every iterator calling
Each iterator will just make a new iterator that needs to go through, but you continue calling getHit() again and again, so you’ll never complete any of the function calls.