When I run my application, it will start populating the "foos" collection. Later instances of "Bar" are created and added to the "bars" collection. Each instance of "Bar" must contain a valid "Foo" instance from the "foos" collection. How do I actual ensure that a Bar is created with an actual reference to a member of a collection ?
If I do this:
I am getting a copy of the object rather than an actual reference.
No, Collections hold references to objects. Since references are just values, List.get(int) returns a copy of the reference, but it points to the original object. You'd have to call clone() on the object (if it supports cloning) or some custom copy() method to make a copy of the object itself.
To ensure that every Bar has a reference to a Foo contained in the foos collection, make the Root object responsible for creating Bars. Since the Root object manages both foos and bars, it should have the responsibility of maintaining integrity between them. This is an aspect of encapsulation.
That's exactly what I was thinking. If you have addBar add the new Bar to the bars collection, then if in the future you modify the collection of foos you can verify that all Bars in bars still reference Foos in foos.
Whoever got anywhere by being normal? Just ask this exceptional tiny ad: