使用ForeignCollection

时间:2012-07-20 20:32:24

标签: android ormlite foreign-collection

我的实体包含以下私有ForeignCollection属性:

@ForeignCollectionField
private ForeignCollection<Order> orderCollection;

private List<Order> orderList;

避免让来电者使用ForeignCollection的最佳方法或通常方法是什么?有没有任何简洁的方法可以将Collections数据返回给调用者?

以下方法如何显示?它允许呼叫者通过List访问数据。你会建议这样做吗?

public List<Order> getOrders() {
    if (orderList == null) {
        orderList = new ArrayList<Order>();
        for (Order order : orderCollection) {
            orderList.add(order);
        }
    }
    return orderList;
}

1 个答案:

答案 0 :(得分:3)

如果可以将签名更改为Collection而不是List,则可以尝试使用Collections.unmodifiableCollection()

public Collection<Order> getOrders()
{
    return Collections.unmodifiableCollection(orderCollection);
}

否则,您使用惰性成员变量的方法很好(假设您不需要同步)。另请注意,您只需使用ArrayList的构造函数来复制源集合中的值:

orderList = new ArrayList<Order>(orderCollection);