Create objects that contains objects of the same type

M

mike

Hi,

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
MyObject.

How can I implement this?

Shall I add a new constructor with:

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

}



All suggestions welcome.

cheers,

//mike
 
M

Mark Space

mike said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,246
Members
46,840
Latest member
BrendanG78

Latest Threads

Top