简体   繁体   English

Java,如何遍历集合 <? extends E> ?

[英]Java, How Iterate through Collection<? extends E>?

so I was given an interface where one method I need to implement gives me a Collection and wants me to "addAll" the data in the collection to my object. 因此为我提供了一个接口,在该接口中,我需要实现的一个方法为我提供一个Collection,并希望我将collection中的数据“ addAll”到我的对象中。 I'm still not sure what exactly a collection is. 我仍然不确定集合到底是什么。 Is it an array list? 它是数组列表吗? I don't belive it is, but can I use a for each loop for each piece of data in the collection? 我不相信它是什么,但是我可以为集合中的每条数据的每个循环使用a吗? Or is there another way to iterate through the collect accessing all of the value. 还是有另一种方法来遍历收集访问所有值的collection。

From the documentation of Collection : Collection的文档中:

The root interface in the collection hierarchy. 集合层次结构中的根接口。 A collection represents a group of objects, known as its elements. 集合表示一组对象,称为其元素。 Some collections allow duplicate elements and others do not. 一些集合允许重复的元素,而另一些则不允许。 Some are ordered and others unordered. 一些是有序的,而其他则是无序的。

You can iterate over it with for or for-each loop or using an Iterator . 您可以使用forfor-each循环或使用Iterator

The most common type of collections are : 最常见的集合类型是:

Iterating a Collection<? extends E> 迭代Collection<? extends E> Collection<? extends E> can be done with an Iterator (and you can get one with Collection.iterator() which can iterate the Collection ) like 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.
    }
}

or, with Java 5+, with a for-each loop like 或者,对于Java 5+,使用for-each循环,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM