Reputation: 382
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:
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
Upvotes: 1
Views: 4309
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
Reputation: 15729
Usethe List's indexOf to get the ID. Drop your idea of an ID for each object._
Upvotes: 0