This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes An Object graph (with a Collection). Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "An Object graph (with a Collection)." Watch "An Object graph (with a Collection)." New topic
Author

An Object graph (with a Collection).

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 761

Hi,

I have a small object graph that looks like this:

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.

Thanks

Pho
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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.
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 761

David,

I think I understand your suggestion. i.e. I need an Root.addBar( .. ) method which will enforce the constraint.

However, in my case; the "foos" collection is a dynamically generated permutation of some other values. So I have to create the "foos" collection first. Then add Bar instances one by one.

Furthermore, Bar instances may share a single Foo.

Regards,

Pho
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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.
 
 
subject: An Object graph (with a Collection).
 
Similar Threads
Trying to access the instance variable of Class Bar from Class Foo --------- why error ?
understanding persistence
Collections-usage design review
(Visitor) two different collections
Garbage Collection!