• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Populating a collection by reference

 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
}

 
Sheriff
Posts: 22789
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic