簡體   English   中英

魔術性地將某些元素從ArrayList中刪除

[英]Some elements are just magically not removed from ArrayList

好的,這是我寫的代碼塊:

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

如果要在訪問列表元素時從列表中刪除元素,建議使用以下模式:

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

它易於使用,而且不容易出錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM