gpt4 book ai didi

java - 有些元素神奇地没有从 ArrayList 中删除

转载 作者:行者123 更新时间:2023-12-01 13:07:09 25 4
gpt4 key购买 nike

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

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/

25 4 0