So I would like to have a way to access an arraylist that an object is in given just that object. Would storing an arraylist within the object be a good way to do it? As far as I know, it would only create a pointer to that arraylist and would not copy all of the data from the arraylist to the object. Is that reasoning correct? Should I refrain from doing so for some other reason?
-
1No. No no no. No. Don't create a circular reference like that, that's asking for trouble. You'll have to revise your design, give us more information and we can help.Jeroen Vannevel– Jeroen Vannevel2013-10-12 00:26:34 +00:00Commented Oct 12, 2013 at 0:26
-
@JeroenVannevel - You are entirely, unbelievably incorrect. There is nothing wrong, in Java with creating circular references. (Of course it may be bad program design in a particular instance, but it is not a serious problem for the JVM.)Hot Licks– Hot Licks2013-10-12 00:33:23 +00:00Commented Oct 12, 2013 at 0:33
1 Answer
Would storing an arraylist within the object be a good way to do it?
It depends on what you mean by "good": it is definitely going to work exactly the way that you describe, so you are fine on that count. However, things may get a little cumbersome if an object gets removed from an array list, or when you must "migrate" an object from one array list to another.
You need to coordinate the removal and clearing out or changing the "my collection" back reference. If yo are not careful, you could even end up with a memory leak, because the whole array list may stay referenced for longer than you have intended.
All this creates a maintenance liability, so if you can think of a way not to do it, you should avoid doing it.