好的,这是我写的代码块:

public ArrayList<Location> possibleMoves() {
   ArrayList<Location> a1 = new ArrayList<Location>(); // an array to contain all       possible locations
   Board testB = new Board(); // a test board to test if locations are valid or not
   // locations have x & y coordinates
          a1.add(new Location(getCurrentLocation().getx() - 1,                    getCurrentLocation().gety() + 1));
          a1.add(new Location(getCurrentLocation().getx() + 1, getCurrentLocation().gety() - 1));
          a1.add(new Location(getCurrentLocation().getx() - 1, getCurrentLocation().gety() - 1));
          a1.add(new Location(getCurrentLocation().getx() + 1, getCurrentLocation().gety() + 1));
          for (int i = 0; i < a1.size(); i++) {
                try {
                    Tower testTower = testB.getGrid()[a1.get(i).getx()][a1.get(i).gety()];
                }catch(ArrayIndexOutOfBoundsException e) {
                    a1.remove(a1.get(i));
                }
         }
         return a1;
      }

最佳答案

删除元素时,以下元素的位置会减少。对i也这样做。并且,您可以只使用remove(int)

for (int i = 0; i < a1.size(); i++) {
    try {
        Tower testTower = testB.getGrid()[a1.get(i).getx()][a1.get(i).gety()];
    } catch(ArrayIndexOutOfBoundsException e) {
        a1.remove(i--);
    }
}

关于java - 魔术性地将某些元素从ArrayList中删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23182737/

10-12 04:05
查看更多