aspose file tools*
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
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: 38865
    
  23
What happens when you try it? Where is the reverse() method?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38865
    
  23
. . . 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: 19696
    
  20

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: 38865
    
  23
Thank you everybody for answering my questions.
archu sweet
Ranch Hand

Joined: Mar 07, 2011
Posts: 66

Thanks all
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Printing a List backwards