my dog learned polymorphism
The moose likes Java in General and the fly likes Populating a collection by reference Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Populating a collection by reference" Watch "Populating a collection by reference" New topic
Author

Populating a collection by reference

Gobind Singh
Ranch Hand

Joined: Aug 04, 2006
Posts: 60
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

Joined: Oct 27, 2005
Posts: 19216

From a usability point of view, the first can be more useful. Instead of limiting to only ArrayLists, you can populate any collection.


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Adam Michalik
Ranch Hand

Joined: Feb 18, 2008
Posts: 128
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Populating a collection by reference
 
Similar Threads
Q from Marcus Green Exam
regarding generics
Bean not working with JSP
Question for Wildcards in Collection
Which reference is better:- Class or interface?