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);
    }
2
  • meteor[i].remove(i); This is calling the remove() method on the meteor object, not the array. Is that what you wanted? Commented Jan 18, 2014 at 17:03
  • I am trying to remove the meteor that visible is false, once it is hit by an object Commented Jan 18, 2014 at 17:10

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

4 Comments

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 I'm trying to pick the most efficint solution. HashSet would be the most efficient way to store a bunch of Meteors. I don't say to overide equals and hashCode because each Meteor should probably be considered distinct.
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 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.
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.