问题描述
我有这个数组列表:
// Add predators
predators = new ArrayList();
for (int i = 0; i < predNum; i++) {
Creature predator = new Creature(random(width), random(height), 2);
predators.add(predator);
}
如何构造语句,以便每 500 帧删除 predators
数组列表中的最后一个元素?它需要某种循环吗?
How can the statement be structured so that the last element from the predators
arraylist is removed every 500 frames? Does it need a loop of some sort?
if (frameCount == 500){
predators.remove(1)
}
推荐答案
如果你已经有一个变量来跟踪你所在的帧,你可以使用这个 if 语句:
If you already have a variable that keeps track of what frame you are on, you can use this if statement:
if (frameCount % 500 == 0) {
predators.remove(1); //use this if you want to remove whatever is at index 1 every 500 frames
predators.remove(predators.size() -1); //use this if you want to remove the last item in the ArrayList
}
由于您使用 1
作为 ArrayList 的 remove 方法的参数,我也这样做了,但请注意,这将始终删除 arrayList 中的第二个对象,因为 arrayList 索引从 0 开始计数.
Since you used 1
as the argument for the remove method of the ArrayList, I did too, but note that this will always remove the 2nd object in the arrayList since arrayList indices start counting at 0.
这只会在每次帧数是 500 的倍数时运行.
This will only run every time the framecount is a multiple of 500.
如果您还没有跟踪 frameCount,则必须将 frameCount++
放入每帧执行的循环中.
If you do not already keep track of the frameCount you will have to put frameCount++
in the loop that is executed every frame.
这篇关于每 500 帧从 ArrayList 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!