1

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?

2
  • 1
    No. 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. Commented 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.) Commented Oct 12, 2013 at 0:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would point out that this structure is incredibly common (and useful) and causes no problem in most cases. It does require thought, if the array is transient in nature, to prevent what is (mistakenly) called a "leak".
@HotLicks You're right about memory leaks misnomer, I do not particularly like the idea of referring to lingering references in Java as "memory leaks", but after seeing it getting used like that for more than a decade I decided to go with the flow, and call it "leaks" too. At least there is some similarity in symptoms to justify the naming :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.