简体   繁体   English

对象从列表中删除自身的最有效方法

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

Let's say we have an array list of objects ObjArray . 假设我们有一个对象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 列表中的每个对象都有一个ID,该ID与其在列表中的位置相对应
  • When object.remove() is called, the object simply simply calls ObjArray.remove(ID) . 调用object.remove() ,对象只是简单地调用ObjArray.remove(ID)
  • ObjArray is parsed from index ID upwards calling ObjArray.get(i).ID --. ObjArray从索引ID向上解析,调用ObjArray.get(i).ID This sets all objects above the removed object to the right ID. 这会将删除的对象上方的所有对象设置为正确的ID。

The other method is of course simply parsing ObjArray until a object match is found. 当然,另一种方法是简单地解析ObjArray直到找到对象匹配为止。

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. ArrayList不是必需的,如果可以使用HashMapLinkedList做得更好,那也就一样。


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. 主JPanel的paint功能由计时器调用。 The paint function loops through the list ObjArray and calls the the object's draw function ( Obj.draw(Graphics g) ). paint函数在列表ObjArray循环并调用对象的绘制函数( 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. 删除对象后,需要将其自身从ObjArray列表中删除。 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. 要提高性能,就需要进行少量的重新设计,可能涉及到Map,但这超出了此问题的范围。

Usethe List's indexOf to get the ID. 使用列表的indexOf获取ID。 Drop your idea of an ID for each object._ 放弃您对每个对象的ID的想法。_

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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