Zwander
Zwander

Reputation: 382

Most efficient way for an object to remove itself from a list

Let's say we have an array list of objects ObjArray.

What is the most efficient way for that object to locate itself within the list, and remove itself from the list?

The way I tend to use is this:

The other method is of course simply parsing ObjArray until a object match is found.

So, is there a better way of doing this? ArrayList is not necessary, if a HashMap or LinkedList can be used to do things better, that's just as good.


More information as requested.

Objects contain information as to where they need to be drawn on screen, and what image is to be drawn. The paint function of the main JPanel is called by a timer. The paint function loops through the list ObjArray and calls the the object's draw function (Obj.draw(Graphics g)).

Objects may be added or removed by clicking.

When an object is removed, it need to remove itself from the ObjArray list. I have stated the two methods that I can think of in the first part.

I would like to know if anyone knows of a more efficient way of doing this.

In short: What's the most efficient way for an item to find/know its position in a list

Upvotes: 1

Views: 4309

Answers (2)

Bohemian
Bohemian

Reputation: 425013

Efficient in terms of code:

list.remove(this); 

The object must be given a reference to the list of course.


Efficient in terms of performance would require a small redesign, probably involving a Map, but is beyond the scope of this question.

Upvotes: 2

user949300
user949300

Reputation: 15729

Usethe List's indexOf to get the ID. Drop your idea of an ID for each object._

Upvotes: 0

Related Questions