【发布时间】:2011-08-15 19:54:39
【问题描述】:
我有一个Item,它有一个方法List<Item> getChildren()(它返回一个不可变列表),对于我拥有的每个项目,我需要创建一个项目列表,然后是其子项。
“cons”(在 Lisp/Scheme 意义上)我的项目以创建新的不可变列表的最快方法是什么?我当然可以做到以下几点,但这似乎是错误的/浪费的:
public List<Item> getItemAndItsChildren(Item item)
{
if (item.getChildren.isEmpty())
return Collections.singletonList(item);
else
{
// would rather just "return cons(item, item.getChildren())"
// than do the following -- which, although straightforward,
// seems wrong/wasteful.
List<Item> items = new ArrayList<Item>();
items.add(item);
items.addAll(item.getChildren());
return Collections.unmodifiableList(items);
}
}
【问题讨论】:
-
您的代码对我来说似乎很不错。问候,Stéphane
-
Java Collections 框架中没有
cons方法(我知道,我也刚刚检查过),但是您可以编写一个名为 cons 的方法来执行此操作,因此您不需要不必到处写丑陋的实现。您还可以“跳过”一行代码:items.add(item);,因为您可以调用采用Collection的ArrayList构造函数。 -
如果您尝试使用
cons,是否真的需要遵守List接口,或者可以放宽该要求吗?List有一些包袱,允许随机访问、反向迭代等。 -
re: guava -- 我认为 guava 可能有一些东西 -- 我已经在使用它,而我不再倾向于使用 Apache Commons。