2014-05-20 9 views
1

我有以下代碼:更好的方法來遍歷這些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,檢查是否存在連續移動。

  1. 我得到一個StackOverflowError。我想我的做事方式不好。我該如何改進它?
  2. 我擔心如果程序找到連續的移動,我會得到java.util.ConcurrentModificationException,因爲我在改變它的同時迭代移動。如何避免這種情況?

回答

0

在列表中放入已刪除項目的索引,並使用這些索引再次迭代以添加新項目。發生是由於遞歸方法調用

1

的計算器錯誤,則必須檢查你的邏輯,任何遞歸方法調用,避免

java.util.ConcurrentModificationException 

您應該使用Collections.synchronizedCollection(系列三)方法,這將提供你是一個線程安全的集合,關於迭代還有一件事,如果你使用的是JAVA 8,那麼你應該檢查流API,它提供了更好和更有效的迭代方法。

+0

@我查了幾次findConsecutiveMoves()函數。我無法找到它的邏輯缺陷。有沒有更好的方法來找到所有連續的? – Shiuyin

+1

這裏是更好的解釋http://stackoverflow.com/questions/10073471/java-how-to-avoid-stackoverflowexception –

+0

另外,在這個問題閱讀德里克Elkins的答案http://stackoverflow.com/questions/951635 /如何對手柄的StackOverflowError式的Java –

0

StackOverflowError意味着您必須進行多次遞歸調用。可能你的findConsecutiveMoves進入一個無限循環(在無限循環中檢查夜間遊戲)。要解決這個問題,請標記已經檢查過的Move,並只檢查下一個還沒有標記的Move。

防止ConcurrentModificationException添加一個列表,您可以在其中存儲可刪除的Move。在完成整個迭代之後,您可以刪除此列表中的每個Move,而不是迭代Move列表。

相關問題