简体   繁体   中英

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. 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? Or is there another way to iterate through the collect accessing all of the value.

From the documentation of 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 .

The most common type of collections are :

Iterating a 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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