迭代这些ArrayLists的更好方法是什么?

时间:2014-05-20 12:21:31

标签: java

我有以下代码:

/**
 * 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的所有可能的Move - 在expand()计算了所有可能的移动之后,如果它们被连接,可能会考虑一些移动中的一些“移动”(例如:移动从a到b。如果我们现在有几个Move a - &gt; b, b - &gt; c,c - &gt; d这将是Move a - &gt; d) - 我需要移除所有那些连续的小动作并设置 - &gt; b到a - &gt; d - 我试图遍历整个移动List并为每个m启动findConsecutiveMoves,检查是否有连续移动。

  1. 我得到了StackOverflowError。我想我的做事方式并不好。我该如何改进呢?
  2. 我担心如果程序找到连续的移动,我会得到一个java.util.ConcurrentModificationException,因为我在更改它时迭代移动。如何避免?

3 个答案:

答案 0 :(得分:1)

由于递归方法调用而发生stackoverflow错误,您必须检查您的逻辑是否有任何递归方法调用,以避免

java.util.ConcurrentModificationException

您应该使用Collections.synchronizedCollection(Collection c)方法,它将为您提供线程安全集合,还有一个关于迭代的事情,如果您使用JAVA 8,那么您应该检查流API,它提供了更好,更有效的方法迭代。

答案 1 :(得分:0)

将已删除项目的索引放入列表中,然后使用这些索引在列表中再次迭代以添加新项目。

答案 2 :(得分:0)

StackOverflowError表示您必须进行多次递归调用。可能你的findConsecutiveMoves进入无限循环(在无限循环中检查nightbours)。要解决此问题,请标记已经检查过的移动,并仅检查下一个尚未标记的移动。

阻止ConcurrentModificationException添加列表,存储可删除的移动。在整个迭代完成后,您可以删除此列表中的每个Move,而不是您的Moves列表的迭代。

相关问题