简体   繁体   中英

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:

  • Every object in the list has an ID that corresponds to its place in the list
  • When object.remove() is called, the object simply simply calls ObjArray.remove(ID) .
  • ObjArray is parsed from index ID upwards calling ObjArray.get(i).ID --. This sets all objects above the removed object to the right ID.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM