This question already has an answer here:
这个问题已经有了答案:
- How do I remove objects from an array in Java? 18 answers
- 如何删除对象在Java数组吗?18个答案
- Removing an element from an Array (Java) [duplicate] 15 answers
- 从数组中删除一个元素(Java)[复制]15个答案。
I am trying to remove a meteor in my game for when it his a bullet but there seems to be an error, and I do not now another method to remove the object.
我试图在我的游戏中移除一颗流星,因为它是一颗子弹,但似乎有一个错误,而我现在没有另一种方法来移除这个物体。
for (int i = 0; i < numA; i++) {
if (meteor[i].isVisible())
meteor[i].move();
else meteor[i].remove(i);
}
3 个解决方案
#1
4
You know, you should actually use a Set
for that. An array is much too inefficient.
你知道,你应该使用一组。一个数组太低效了。
To do this, instead of declaring an array:
这样做,而不是声明一个数组:
private Meteor[] meteor = new Meteor[10];
declare a Set
:
声明一组:
private Set<Meteor> meteor = new HashSet<Meteor>();
You can add meteors:
您可以添加流星:
meteor.add(newMeteor);
and remove them:
和删除:
meteor.remove(meteorToRemove);
and check if they are in the set:
检查它们是否在集合中:
if (meteor.contains(met))
and iterate through them:
和遍历:
for (Meteor m : meteor)
#2
1
Apache has a commons utility method in ArrayUtils
that could help. It works like this:
Apache在ArrayUtils中有一个可以帮助的commons实用程序方法。是这样的:
array = ArrayUtils.removeElement(meteor, elementToDelete)
= ArrayUtils数组。elementToDelete removeElement(流星)
Check out the docs for more info: Apache Docs
更多信息查看文档:Apache文档
#3
0
array only solution
for (int i = 0; i < numA; i++) {
if (meteor[i].isVisible())
meteor[i].move();
else {
Meteor[] result = new Meteor[meteor.length - 1];
System.arraycopy(meteor, 0, result, 0, i);
if (meteor.length != i) {
System.arraycopy(meteor, i + 1, result, i, meteor.length - i - 1);
}
meteor = result;
}
}
#1
4
You know, you should actually use a Set
for that. An array is much too inefficient.
你知道,你应该使用一组。一个数组太低效了。
To do this, instead of declaring an array:
这样做,而不是声明一个数组:
private Meteor[] meteor = new Meteor[10];
declare a Set
:
声明一组:
private Set<Meteor> meteor = new HashSet<Meteor>();
You can add meteors:
您可以添加流星:
meteor.add(newMeteor);
and remove them:
和删除:
meteor.remove(meteorToRemove);
and check if they are in the set:
检查它们是否在集合中:
if (meteor.contains(met))
and iterate through them:
和遍历:
for (Meteor m : meteor)
#2
1
Apache has a commons utility method in ArrayUtils
that could help. It works like this:
Apache在ArrayUtils中有一个可以帮助的commons实用程序方法。是这样的:
array = ArrayUtils.removeElement(meteor, elementToDelete)
= ArrayUtils数组。elementToDelete removeElement(流星)
Check out the docs for more info: Apache Docs
更多信息查看文档:Apache文档
#3
0
array only solution
for (int i = 0; i < numA; i++) {
if (meteor[i].isVisible())
meteor[i].move();
else {
Meteor[] result = new Meteor[meteor.length - 1];
System.arraycopy(meteor, 0, result, 0, i);
if (meteor.length != i) {
System.arraycopy(meteor, i + 1, result, i, meteor.length - i - 1);
}
meteor = result;
}
}