2

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 Answers3

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)
tbodt
  • 16,609
  • 6
  • 58
  • 83
  • 3
    Admittedly, anything that is a `Collection` has a `remove` and `contains` method, not just a `Set`. You're only then (trying to) guarantee that duplicate `Meteor` objects aren't placed into the collection. Not sure if that's what is desired, but for this to work to its fullest potential, `equals()` and `hashCode()` have to be overridden in `Meteor`. – Makoto Jan 18 '14 at 17:09
  • @Makoto I'm trying to pick the most efficint solution. `HashSet` would be the most efficient way to store a bunch of `Meteor`s. I don't say to overide `equals` and `hashCode` because each `Meteor` should probably be considered distinct. – tbodt Jan 18 '14 at 17:12
  • It isn't going to work as well as you think if two instances of `Meteor` hash to the same value. That's precisely why you have to override hashCode (and you really should override equals, since that's the general contract of overriding those two). There is a difference between efficient and broken code. – Makoto Jan 18 '14 at 17:13
  • @Makoto The default implementation of `hashCode` makes it very, very unlikely that two different instances of `Meteor` has to the same value. If they do, `equals` is overridden to use the `==` operator. There can't possibly be a problem with this. – tbodt Jan 18 '14 at 17:15
1

Apache has a commons utility method in ArrayUtils that could help. It works like this:

array = ArrayUtils.removeElement(meteor, elementToDelete)

Check out the docs for more info: Apache Docs

Durandal
  • 5,575
  • 5
  • 35
  • 49
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;
    }
}
MariuszS
  • 30,646
  • 12
  • 114
  • 155