gpt4 book ai didi

Java,如何遍历 Collection?

转载 作者:行者123 更新时间:2023-11-30 06:14:55 30 4
gpt4 key购买 nike

所以我得到了一个接口(interface),其中我需要实现的一个方法为我提供了一个集合,并希望我将集合中的数据“全部添加”到我的对象中。我仍然不确定集合到底是什么。它是一个数组列表吗?我不相信它是,但我可以为集合中的每条数据使用 for each 循环吗?或者是否有另一种方法来遍历收集访问所有的值。

最佳答案

迭代 Collection<? extends E>可以用 Iterator 来完成(你可以用 Collection.iterator() 得到一个,它可以迭代 Collection )像

public static <E> void iterateWithIterator(Collection<? extends E> coll) {
Iterator<? extends E> iter = coll.iterator();
while (iter.hasNext()) {
E item = iter.next();
// do something with the item.
}
}

或者,对于 Java 5+,使用 for-each loop喜欢

public static <E> void forEachIterate(Collection<? extends E> coll) {
for (E item : coll) {
// do something with the item.
}
}

关于Java,如何遍历 Collection<?延伸 E>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585269/

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