Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is this code giving compilation error on red line?

 
Dishi Jain
Ranch Hand
Posts: 46
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
Java PHP
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Dishi Jain
Ranch Hand
Posts: 46
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the clarification.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic