[英]Removing objects by reference in Java
This is an odd question. 这是一个奇怪的问题。 But here goes.
但是这里。
I have object X, which gets inserted, in an array, in a hashtable, within another object (container object) It represents instances of X at point P in 3d space. 我有对象X,该对象在数组中,在哈希表中的另一个对象(容器对象)中插入,它表示3d空间中P点的X实例。
Sometimes I'll want to refresh the X's at a given P. This is simple enough - recall the point P from the table and manipulate the array directly. 有时我想刷新给定P处的X。这很简单-从表中调出P点并直接操作数组。
Now say that those X's are part of a Y - fragments of a Y to be precise. 现在说那些X是Y的一部分-确切地说是Y的片段。 Let's say a given Y goes away.
假设给定的Y消失了。 Now, if Y goes away all X's that are attached to it should go away as well, right?
现在,如果Y消失了,所有与其相连的X也应该消失,对吗?
To be precise, object Y is being removed conceptually from the model. 确切地说,从概念上将对象Y从模型中删除。 Whether it is actually deleted or not is immaterial (it might get stored somewhere else, for instance.) But the salient point is, aside from checking every point in vicinity of Y for its X's, how do I properly remove them from the hashtable?
是否真正删除它并不重要(例如,它可能存储在其他地方。)但是,最重要的一点是,除了检查Y附近的每个点的X之外,如何从哈希表中正确删除它们?
This is actually a general question about references as a whole. 这实际上是关于引用整体的一个普遍问题。 There are other situations where more than one reference to an object exists, and I would like to be able to remove that object quickly without having to navigate to it in its other locations.
在其他情况下,存在对一个对象的多个引用,并且我希望能够快速删除该对象而不必在其他位置导航到该对象。
This means that when one referencing class removes the object, the object should be 'removed' universally; 这意味着,当一个引用类删除该对象时,应该通用地“删除”该对象。 none of the other lists should retain reference to it.
其他列表均不应保留对其的引用。
In Java this problem is often addressed with WeakReference<T>
objects: if you do not want a reference to prevent an object X
from being collected, make it a WeakReference<X>
: Java will null it out when X
is no longer strongly referenced from anywhere else. 在Java中,此问题通常通过
WeakReference<T>
对象解决:如果您不想通过引用阻止对象X
收集,请将其WeakReference<X>
:当不再强烈引用X
时,Java会将其无效从其他任何地方。
For example, you can make a List<X>
that keeps all objects that are alive, and make all other references to X
weak. 例如,您可以创建一个
List<X>
,使所有活动对象保持活动状态,并使对X
所有其他引用均变弱。 When an object is removed from the list and its last strong reference is gone, it becomes collectable regardless of the number of weak references to it. 当一个对象从列表中删除并且它的最后一个强引用消失时,无论有多少个弱引用,它都可以被收集。 The obvious downside is that you need to pay attention to nulls before dereferencing each weak reference.
明显的缺点是,在取消引用每个弱引用之前,您需要注意null。 At this point, Java does all reference tracking for you;
至此,Java为您完成了所有参考跟踪。 all you need to do is to clean out the weak references that went null, which is much easier than searching through a large number of lists.
您所需要做的就是清除弱化为null的弱引用,这比在大量列表中进行搜索要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.