有些元素只是神奇地没有从ArrayList中删除

时间:2014-04-20 13:00:15

标签: java arraylist try-catch game-engine

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

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;
      }

2 个答案:

答案 0 :(得分:1)

删除元素时,会减少以下元素的位置。这也是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--);
    }
}

答案 1 :(得分:0)

如果您想在访问其元素时从List中删除元素,我建议使用以下模式:

Iterator<Location> locationsIt = a1.iterator();
while (locationsIt.hasNext()) {
  Location location = locationsIt.next();
  try {
    Tower testTower = testB.getGrid()[location.getx()][location.gety()];
  } catch(ArrayIndexOutOfBoundsException e) {
    locationsIt.remove();
  }
}

它易于使用,并且不容易出错。