user1086498
user1086498

Reputation:

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.

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.

Now say that those X's are part of a Y - fragments of a Y to be precise. Let's say a given Y goes away. Now, if Y goes away all X's that are attached to it should go away as well, right?

To be precise, object Y is being removed conceptually from the model. 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?

  1. They're part of an array, so another Y's X's will likely be there too, so we need to remove just the X's which belong to the given Y.
  2. We can search the hashtable structure for the X's that belong to Y - for instance we can figure out all of the points P that Y would occupy, and then pull out those containers and remove all of the X's that are attached to our Y.
  3. Can we remove them directly? If Y has a list of its X's, can they be removed by reference, without having to go through the effort of searching the table?

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.

Upvotes: 1

Views: 2188

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

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.

For example, you can make a List<X> that keeps all objects that are alive, and make all other references to X weak. 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. At this point, Java does all reference tracking for you; 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.

Upvotes: 1

Related Questions