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.
Asked
Active
Viewed 5,040 times
3
-
3Collection implements the `Iterator` interface, doesn't it? Couldn't you use that to **Iterate** through? – SteveK Apr 12 '15 at 02:28
-
An `ArrayList` is a [collection](https://docs.oracle.com/javase/tutorial/collections/). You should google "java collections"; google helps in situations like this. – Vince Apr 12 '15 at 02:28
-
possible duplicate of [Java: Best way to iterate through an Collection (here ArrayList)](http://stackoverflow.com/questions/5228687/java-best-way-to-iterate-through-an-collection-here-arraylist) – John Apr 12 '15 at 02:29
-
@Steve `interface Collection extends Iterable` but more less yes to what you say. ; ) – Radiodef Apr 12 '15 at 03:56
2 Answers
5
Iterating a 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.
}
}

Elliott Frisch
- 198,278
- 20
- 158
- 249
-
For some reason in my case I get a compile error: error: incompatible types: Class extends E> cannot be converted to E. Any thoughts? Android/Java-7 – TahoeWolverine Jun 06 '18 at 20:06
-
PECS. Producer Extends, Consumer Super. Where you consume the collection, it should probably be `Collection super E> coll` – Elliott Frisch Jun 06 '18 at 20:07
3
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 :

Jean-François Savard
- 20,626
- 7
- 49
- 76