• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Printing a List backwards

 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt in the following code :


List list = new ArrayList();
list.add("1"); list.add("2"); list.add("3");
for (Object obj: reverse(list)) // can't we declare like this
System.out.print(obj + ", ");
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when you try it? Where is the reverse() method?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and your original thread title bore no relationship to its contents. I have changed it.
 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@campbell :

 
Callum Ludwig
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Archu,

Wrapping source code examples in code blocks makes for a nicer easier to read output for forum posts.



Where is the reverse method? Do you mean the static method found in the java.util.Collections class?



You can't call the static method reverse within the enhanced for loop as it returns void. It actually updates the loop passed in by the reference. Hence why I called reverse and then was able to use the list directly in the enhanced for loop.

You should get to know the classes and interfaces found in the java.util.* package, as there are heaps and heaps of awesome stuff already implemented to help Java developers.

Hope all this helps.
 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@callum : thanks a ton for your explanation...
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
archu sweet wrote:@campbell :


The for-each loop works with Iterable, not Iterator. There's a difference. Make the reverse method return List (and so "return list" instead of "return list.iterator()") and that code should work, since List extends Iterable (indirectly).
 
Campbell Ritchie
Sheriff
Pie
Posts: 49849
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you everybody for answering my questions.
 
archu sweet
Ranch Hand
Posts: 66
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic