This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Printing a List backwards Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Printing a List backwards" Watch "Printing a List backwards" New topic
Author

Printing a List backwards

archu sweet
Ranch Hand

Joined: Mar 07, 2011
Posts: 66

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

Joined: Oct 13, 2005
Posts: 38033
    
  22
What happens when you try it? Where is the reverse() method?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033
    
  22
. . . and your original thread title bore no relationship to its contents. I have changed it.
archu sweet
Ranch Hand

Joined: Mar 07, 2011
Posts: 66

@campbell :

Callum Ludwig
Greenhorn

Joined: Feb 20, 2011
Posts: 13
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

Joined: Mar 07, 2011
Posts: 66

@callum : thanks a ton for your explanation...
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19654
    
  18

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).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38033
    
  22
Thank you everybody for answering my questions.
archu sweet
Ranch Hand

Joined: Mar 07, 2011
Posts: 66

Thanks all
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Printing a List backwards
 
Similar Threads
Why is this code giving compilation error on red line?
I am getting "void type not allowed here" error
getting the value of string array out of object array
problem with retriving values from hashtable
help me