Create objects that contains objects of the same type

Discussion in 'Java' started by mike, Mar 3, 2009.

  1. mike

    mike Guest


    We are working with a protocol that can have one/more object/-s of the
    same type within that object.

    Normally we have:

    public class MyObject{

    private String name = null;
    private String value = null;

    public MyObject(String name,String value){


    //getters/ setters for name and value.


    Now each of these objects can contain one/ more objects of type

    How can I implement this?

    Shall I add a new constructor with:

    public MyObject(String name,String value, ArrayList<MyObjects> objects)


    All suggestions welcome.


    mike, Mar 3, 2009
    1. Advertisements

  2. Mark Space

    Mark Space Guest

    mike wrote:

    > Shall I add a new constructor with:
    > public MyObject(String name,String value, ArrayList<MyObjects> objects)
    > {
    > }

    If you have setters right now, then MyObject is not immutable, so I
    don't see any reason to require lots of constructors. Just make a pair
    of methods like getters and setters.

    public void addToList( MyObject o ) {
    list.add( o );

    public MyObject getFromList( int i ) {
    return list.get( i );

    I think you will need these anyway, so you might as well use them.
    There's nothing wrong with your constructor, it's just very likely
    you'll need the above setters and getters anyway, so you could just use
    them instead.

    OTOH, if your objects ARE in a List to begin with, you above constructor
    could be a great convenience, so if it works, do it. I'm just trying to
    keep your design as simple as possible. And obviously, if you DON'T ever
    modify the list after you create the object, then use the constructor
    method and leave the extra getters and setters off. Really, it depends
    on your design.

    Finally, if you do modify the list as the program runs, consider
    implementing a List interface:

    public MyObject implements List { // or extends AbstractList

    You might gain some utility from being able to treat your objects as
    standard lists. The downside to this is the List is now a public part
    of the MyObject and will have to be maintained forever or refactored out
    later at some cost.
    Mark Space, Mar 3, 2009
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page