Koerr
Koerr

Reputation: 15723

Why cant I use an Iterator this way?

Iterator<String> iterator=...

//right way
for (Iterator<String> i = iterator; i.hasNext(); ){
    System.out.println(i.next());
}

//why can't?
for(String i:iterator){         
}

Reference:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html

Upvotes: 0

Views: 92

Answers (4)

Thilo
Thilo

Reputation: 262504

You can do more compactly:

for(String i:list){
}  

The syntax is only for Iterables (and arrays), not for their Iterators directly (and also not for Enumerations).

Why not? I don't know... Maybe too much complexity/effort (in the compiler implementation) for a "rare" case. Or edge-cases that would cause trouble (such as an Iterable that is also an Iterator, I think some people make such beasts).

Maybe try libraries like Google Guava to get some more convenient ways to work with Iterators, Collections, and friends.

Upvotes: 4

pauljwilliams
pauljwilliams

Reputation: 19225

You can only use the for loop syntax with objects that implement the Iterable interface.

Iterators are not iterable.

Upvotes: 2

JR Galia
JR Galia

Reputation: 17269

    for(String i:list){
        //
    }

Upvotes: -1

Ed Morales
Ed Morales

Reputation: 1037

The compiler checks the syntax for the for enhanced and requires that the expression after the colon returns an object that implements the Iterable interface. Iterator doesn't implement it.

Upvotes: 2

Related Questions