Frosted Cupcake
Frosted Cupcake

Reputation: 1970

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.

Upvotes: 5

Views: 419

Answers (3)

Crazyjavahacking
Crazyjavahacking

Reputation: 9707

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.

Upvotes: 5

ConMan
ConMan

Reputation: 1652

You wouldnt ever want to iterate through an integer, nor could you ever do such a thing. An integer is a single entity, whereas the iterable interface is in reference to a colleciton of entities. For example:

List<Integer> intList = new ArrayList<Integer>();

for (Integer i : intList) {
   System.out.println(i);
}

Upvotes: 3

khelwood
khelwood

Reputation: 59185

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.

Upvotes: 3

Related Questions