wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why is this code giving compilation error on red line? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why is this code giving compilation error on red line?" Watch "Why is this code giving compilation error on red line?" New topic
Author

Why is this code giving compilation error on red line?

Dishi Jain
Ranch Hand

Joined: Jan 16, 2011
Posts: 46

java.lang.Pass2

public class Pass2 {
public static Iterator reverse(List list) {
Collections.reverse(list);
return list.iterator();
}
public static void main(String[] args) {
List list = new ArrayList();
list.add("1"); list.add("2"); list.add("3");
for (Object obj: reverse(list))
System.out.print(obj + ", ");
}
}

It says Can only iterate over an array or an instance of java.lang.Iterable
What should be the correct way of coding this then?
Malte Wannerskog
Ranch Hand

Joined: Jan 06, 2011
Posts: 92

You cannot apply for-each to an Iterator.

This is the correct way to traverse through an Iterator.




Update:

Or you could of course skip the Iterator and just do it like this:


OCPJP (310-065) - 88%
Dishi Jain
Ranch Hand

Joined: Jan 16, 2011
Posts: 46

Thanks for the clarification.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why is this code giving compilation error on red line?