How can I use the for-each loop for classes that do not implement Iterable

I read Collections from the Complete Reference , and then I came across this statement

Collection interface

The collection interface is the foundation on which collections are assembled. The structure is built because it must be implemented by any class that defines the collection. A collection is a common interface that this declaration has: interface Collection<E> . Here E indicates the type of objects that will be stored in the collection. A collection extends Iterable interface.This means that all collections can cyclically use the for-each style for the loop. (Recall that only classes that implement Iterable can be looped through with for).

The last two lines say that only those classes that implement the Iterable interface can loop through the for loop. But, I think that the class of the object does not implement an iterable interface, then how can we use the for-each loop in the case of strings, integers, etc.

+5
source share
3 answers

It's true. java.lang.Object does not implement the Iterable<T> interface.

We can iterate through objects, because the owner of the object (e.g. Collection ) implements Iterable<T> automatically, not necessarily part of the objects in the collection.

+5
source

If you iterate through a set of strings or integers, this is an iterable collection, not a string or integer. Elements in an iteration should not be iterable; the container does.

+3
source

You would never want to iterate through an integer, and you could never do such a thing. An integer represents a single object, while an iterable interface refers to a collection of objects. For instance:

 List<Integer> intList = new ArrayList<Integer>(); for (Integer i : intList) { System.out.println(i); } 
+3
source

All Articles