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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With