Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

An Object graph (with a Collection).

 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic