[英]Better Way to iterate through those 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的所有可能移动。-expand()计算所有可能的移动后,如果这些“移动”已连接,则其中几个“移动”可能会成为一个移动(例如:一个移动从a移到b。如果我们现在有几个移动a-> b,b-> c,c-> d,这就是移动a-> d)-我需要删除所有这些小的连续移动并将a-> b设置为a-> d-我正在尝试遍历整个移动列表,并为每个m启动findConsecutiveMoves,检查是否有连续的移动。
由于递归方法调用而发生stackoverflow错误,您必须检查逻辑是否有任何递归方法调用,以避免
java.util.ConcurrentModificationException
您应该使用Collections.synchronizedCollection(Collection c)方法,该方法将为您提供线程安全的集合。关于迭代的另一件事,如果您使用的是JAVA 8,则应签出流API,它提供了更好而有效的迭代方法。
将已删除项目的索引放入列表,然后使用这些索引在列表上再次进行迭代以添加新项目。
StackOverflowError
意味着您必须进行许多递归调用。 可能您的findConsecutiveMoves进入了无限循环(在无限循环中检查夜行)。 要解决此问题,请标记您已选中的Moves,然后仅选中尚未标记的下一个Moves。
防止ConcurrentModificationException
添加一个列表,在其中存储可删除的Move。 在完成整个迭代之后,您可以删除此列表中的每个Move,而您并不是Moves列表的迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.