gpt4 book ai didi

java - com.google.common.collect.Lists.newArrayList 丢弃我的元素

转载 作者:行者123 更新时间:2023-12-01 17:49:47 25 4
gpt4 key购买 nike

我有这个代码:

int size = Iterables.size(components);
log.info("Number of components found (before convert): " + size);

List<Component> listOfComponents = Lists.newArrayList(components);
size = listOfComponents.size();
log.info("Number of components found (after convert): " + size);

for (Component component : listOfComponents) {
log.info("component : " + component);
}

其中Component是:org.sonatype.nexus.repository.storage.Component

当我运行它时,它会打印:

Number of components found (before convert): 2
Number of components found (after convert): 0

因此,在我将可迭代对象转换为列表后,元素不再存在。而且我从来没有进入以下循环。

为什么元素没有被复制到列表中,这就是文档所说的:

Creates a mutable ArrayList instance containing the given elements; a very thin shortcut for creating an empty list then calling Iterables.addAll.

最佳答案

您需要了解 Guava 的 Iterables 返回的 Iterable是一个一次性的可迭代对象。 事实证明,您的 Iterable 是一个一次性的可迭代对象。1 在迭代一次之后,它不会在后续迭代中抛出,而是空的。

因此,您的召唤 Iterables.size它有效地清空了 Iterable,这就是生成的 ArrayList 为空的原因。

相反,您应该尽快将 Iterable 转储到 ArrayList

<小时/>

1 句子被删除,因为事实证明 Guava 遵守了 Iterable 的事实上的标准 iterable multiple times .

关于java - com.google.common.collect.Lists.newArrayList 丢弃我的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51648798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com