0
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class TryMe {

    public static void main(String args[]) {

        List list = new LinkedList<String>();

        list.add("one");
        list.add("two");
        list.add("three");

        Collections.reverse(list);

        Iterator iter = list.iterator();

        for (Object o : iter) {
            System.out.print(o + " ");
        }
    }
}

This question is from SCJP , i have problem in understanding iterator and iterable.

I know iterator is an interface with iterator method. Why we cant use for each loop in case of iterator? Compiler says: can only iterate over an array or an instance of java.lang.iterable. what is this? i tried alot to search but didnt get answer

Please Reply

Pshemo
  • 122,468
  • 25
  • 185
  • 269
user2985842
  • 437
  • 9
  • 24
  • 2
    Because an [`Iterator`](http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html) **is not** an [`Iterable`](http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html). Those are two different interfaces. – Luiggi Mendoza Mar 13 '14 at 20:55
  • you iterate on iterable not on iterator – jmj Mar 13 '14 at 20:56
  • related: http://stackoverflow.com/questions/6863182/what-is-the-difference-between-iterator-and-iterable-and-how-to-use-them –  Mar 13 '14 at 20:57
  • @RC. it's not related, it's a possible dup – Luiggi Mendoza Mar 13 '14 at 20:59
  • By the way, the compiler is pretty clear about your problem: *can only iterate over an **array** or **an instance of `java.lang.Iterable`***, so you can't iterate over an `Iterator` – Luiggi Mendoza Mar 13 '14 at 21:00

2 Answers2

3

There is a difference between Iterable and Iterator. An Iterator is an object that iterates over elements of another object, the Iterable. An Iterable is what contains the elements and supplies the Iterator object (with the iterator() method) that iterates over the Iterable's elements.

The enhanced for loop must take an Iterable, so that it can call iterator() to get a guaranteed new Iterator to iterate over the elements implicitly.

This is enforced by the JLS, Section 14.14.2:

The enhanced for statement has the form:

EnhancedForStatement:
    for ( FormalParameter : Expression ) Statement

and

The type of the Expression must be Iterable or an array type (§10.1), or a compile-time error occurs.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
0

The List is Iterable, the Iterator is not.

This will work:

    for (Object o : list) {
Jonas Fagundes
  • 1,519
  • 1
  • 11
  • 18