• Post Reply Bookmark Topic Watch Topic
  • New Topic

Populating a collection by reference  RSS feed

 
Gobind Singh
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to determine if there is any advantages/disadvantages between using the followingg approaches to populate a collection.

Firstly doing pass-by-reference:

Collection col = new ArrayList();

populateCollection(col);


//carry on using col in someway

....
...

public void populateCollection(Collection c)
{
//add to the collection
}


Or is it better to do the following:

Collection d = populateCollection();

//carry on using col in someway

....
...

publiic Collection populateCollection()
{
Collection col = new ArrayList();
//add stuf to col
}

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From a usability point of view, the first can be more useful. Instead of limiting to only ArrayLists, you can populate any collection.
 
Adam Michalik
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Besides of what Rob said, having a populateCollection(col) method gives you the ability to pass a prepopulated collection and just add something more to it. On the other hand, you may wish to be sure to have a collection containing only the values added by the populateCollection() method. If so, you'd have to check in the first case if the collection is empty. It depends on what you want to achieve and what constraint you want to have on the collection.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!