我有以下代碼:更好的方法來遍歷這些ArrayLists?
/**
* Calculates all correct Moves for Figure f which are possible
* @param f the Figure for which you want to check it's moves
* @return
*/
public ArrayList<Move> checkMoves(Figure f) {
ArrayList<Move> moves = this.expand(f.getLocation(), new ArrayList<Move>(), false, this.getPlayer(f.getOwner()));
// Fix the wrongly calculated moves
for(Move m : moves) {
moves = this.jumpFix(moves, m);
}
return moves;
}
/**
* Takes a look into all calculated moves and finds those which should be seen as one move, but are still
* considered to be more than one move (several jumps in one move)
*/
private ArrayList<Move> jumpFix(ArrayList<Move> moves, Move m) {
ArrayList<Move> consecutive = this.findConsecutiveMoves(moves, new ArrayList<Move>(), m);
if(consecutive.size() > 0) {
m.getTarget().setX(consecutive.get(consecutive.size() - 1).getTarget().getX());
m.getTarget().setY(consecutive.get(consecutive.size() - 1).getTarget().getY());
}
for(Move i : consecutive) {
moves.remove(i);
m.addStop(i.getTarget());
}
return moves;
}
/**
* Finds all consecutive moves to the given move m, that share their start and target cells
*/
public ArrayList<Move> findConsecutiveMoves(ArrayList<Move> moves, ArrayList<Move> deleteable, Move m) {
for(Move n : moves) {
if(n.getStart().equalTo(m.getTarget())) {
deleteable.add(n);
deleteable = this.findConsecutiveMoves(moves, deleteable, n);
}
}
return deleteable;
}
說明: - checkMoves計算F 給定圖所有可能的行動 - 擴大後()計算所有可能的行動,數那些「動作」可能sondered一招,如果他們連接(例如:移動從a到b。如果我們現在有幾個移動a - > b,b - > c,c - > d這將是移動a - > d) - I需要刪除所有這些小的連續移動,並將 - > b設置爲 - > d - 我試圖迭代整個移動列表,併爲每個m開始findConsecutiveMoves,檢查是否存在連續移動。
- 我得到一個StackOverflowError。我想我的做事方式不好。我該如何改進它?
- 我擔心如果程序找到連續的移動,我會得到java.util.ConcurrentModificationException,因爲我在改變它的同時迭代移動。如何避免這種情況?
@我查了幾次findConsecutiveMoves()函數。我無法找到它的邏輯缺陷。有沒有更好的方法來找到所有連續的? – Shiuyin
這裏是更好的解釋http://stackoverflow.com/questions/10073471/java-how-to-avoid-stackoverflowexception –
另外,在這個問題閱讀德里克Elkins的答案http://stackoverflow.com/questions/951635 /如何對手柄的StackOverflowError式的Java –