Reputation: 4917
My entity contains the following private ForeignCollection
attribute:
@ForeignCollectionField
private ForeignCollection<Order> orderCollection;
private List<Order> orderList;
What is the best way or usual way to avoid a having a caller use a ForeignCollection
? Is there any neat way to return the Collections
data to a caller?
How does the following method look? It allows a caller to access the data via a List
. Would you recommend doing it this way?
public List<Order> getOrders() {
if (orderList == null) {
orderList = new ArrayList<Order>();
for (Order order : orderCollection) {
orderList.add(order);
}
}
return orderList;
}
Upvotes: 4
Views: 2128
Reputation: 37516
If it's ok to change the signature to Collection
rather than List
, you could try using Collections.unmodifiableCollection().
public Collection<Order> getOrders()
{
return Collections.unmodifiableCollection(orderCollection);
}
Otherwise, your approach of using a lazy member variable is fine (provided you don't need synchronization). Also, note that you can just use the constructor of ArrayList
to copy the values from the source collection:
orderList = new ArrayList<Order>(orderCollection);
Upvotes: 3