I was reading Collections From The Complete Reference and then I encountered this statement
The Collection Interface
The Collection interface is the foundation upon which the Collections Framework is built because it must be implemented by any class that defines a collection. Collection is a generic interface that has this declaration:
interface Collection<E>
. Here, E specifies the type of objects that the collection will hold. Collection extends the Iterable interface.This means that all collections can be cycled through by use of the for-each style for loop.(Recall that only classes that implement Iterable can be cycled through by the for).
In the last two lines,it is written that only those classes which implement the Iterable interface can be cycled through the for loop. But,I guess that the object class does not implement the iterable interface,then how we are able to use the for-each loop in case of Strings,integers etc.
That's true. java.lang.Object
does not implement the Iterable<T>
interface.
We can iterate through objects because the object holder (e.g. Collection
) implements the Iterable<T>
automatically, not necessarily the objects part of the collection.
If you are iterating through a collection of strings, or integers, it is the collection that is iterable, not the string or the integer. The items in the iteration don't have to be iterable; the container does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With