Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to use the for-each loop for classes that do not implement Iterable

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.

like image 736
Frosted Cupcake Avatar asked Jul 03 '15 10:07

Frosted Cupcake


2 Answers

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.

like image 119
Crazyjavahacking Avatar answered Sep 19 '22 19:09

Crazyjavahacking


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.

like image 30
khelwood Avatar answered Sep 22 '22 19:09

khelwood