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

Java 有些元素只是神奇地没有从ArrayList中删除,java,arraylist,try-catch,game-engine,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

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

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;
      }
public ArrayList possibleMoves(){
ArrayList a1=新的ArrayList();//包含所有可能位置的数组
Board testB=new Board();//测试位置是否有效的测试板
//位置具有x和y坐标
a1.添加(新位置(getCurrentLocation().getx()-1,getCurrentLocation().gety()+1));
a1.添加(新位置(getCurrentLocation().getx()+1,getCurrentLocation().gety()-1));
a1.添加(新位置(getCurrentLocation().getx()-1,getCurrentLocation().gety()-1));
a1.添加(新位置(getCurrentLocation().getx()+1,getCurrentLocation().gety()+1));
对于(int i=0;i
移除元件时,以下元件的位置将减小。对
i
也执行此操作。而且,您只需使用
remove(int)

for(int i=0;i
如果要在访问元素时从中删除元素,我建议使用以下模式:

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();
  }
}
Iterator locationsIt=a1.Iterator();
while(locationsIt.hasNext()){
Location=locationsIt.next();
试一试{
Tower testTower=testB.getGrid()[location.getx()][location.gety()];
}捕获(阵列索引边界外异常e){
位置SIT.移除();
}
}

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

当您从列表中删除一个元素时,大小会减小,因此您可能不会检查它的所有元素。我将传递到方法“删除一个元素而不是索引”,那么现在该怎么办?我要说的是,如果删除一个元素(如果您使用
remove(Object o))
删除(int-index)
,可以将大小减小一。如果您看一下这个示例,您会期望列表中的所有元素都被删除,但事实并非如此。
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();
  }
}