Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: returning a collection

What's the best way to return a collection in Java?

Should I allow the caller to provide a collection to add to? Or just return a List<> or Set<> of items? Or both?

public class Item { ... }

public class SomeOtherClass
{
  private List<Item> myItems;

  public List<Item> getItems()
  { 
     return Collections.unmodifiableList(this.myItems); 
  }
  public void collectItems(Collection<? super Item> target)
  {
     target.addAll(myItems);
  }
}

note: the above example assumes the pre-existence of a list that can be instantly returned. I am also interested in the appropriate answer when such a list does not previously exist and must be generated when the caller calls getItems() or collectItems(). (I have renamed collectItems based on the point raised by Mykola.)

like image 420
Jason S Avatar asked Feb 01 '10 16:02

Jason S


1 Answers

It is better (unless some performance issues) to return result in a functions via return. In that way it is more clear what is going on.

If you choose second option (fill client's collection) than it would be better to rename function from getItems to something like fillWithItems to avoid ambiguous code.

Also don't forget about JavaBeans and its convention.

like image 145
Mykola Golubyev Avatar answered Oct 02 '22 22:10

Mykola Golubyev