我正在學習java中的任務,並且遇到了一個錯誤,我無法找到答案。 不知何故,當我對由iterator.next()
返回的對象調用gethit()
方法時,出現堆棧溢出異常。 我懷疑因爲gethit()
方法(在這個特定情況下)遞歸調用自己。儘管如此,我認爲堆棧溢出很奇怪,因爲遞歸深度只有2或3層,而我的對象不會使用過多的內存。Java堆棧溢出,因爲遞歸方法調用
的shoot()
方法使得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);
}
第一個呼叫的getHit()
方法本身遞歸調用。
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();
}
「遞歸只能達到2或3級」 - 你確定嗎? – 2012-07-25 20:31:23