Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes Print attributes of ListArray in reverse Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Print attributes of ListArray in reverse" Watch "Print attributes of ListArray in reverse" New topic
Author

Print attributes of ListArray in reverse

Mark Hughes
Ranch Hand

Joined: Jul 14, 2006
Posts: 146
Hey Guys,
thanks for all your help thus far, really learning alot!

I have a ListArray called lines 2 which contains some info, now i can print all the information in the ListArray out easily from position 0 to the end of the array doing as follows;


Works grand but i want to print from the end of the list to the top starting at the last bit of information in the ListArray, i tried this;
[/code]
for (int i = lines2.size(); i > 0; i--)
{
System.out.println(lines2.get(i));
}
[/code]

But it causes an error, I thought by making i equal the size of the array and having as long as i is greater than 0 to decrement down to 0 from the end of the list it would print i from last position in array, am i thinking about it wrong?

Thanks Mark
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

ArrayList, not ListArray, yes?

The only problem here is an "off-by-one error." The last element is at index size()-1, not size(), and the first element is at 0, not 1; so a proper loop could look like

for (int i=lines2.size()-1; i >= 0; --i)


[Jess in Action][AskingGoodQuestions]
Mark Hughes
Ranch Hand

Joined: Jul 14, 2006
Posts: 146
Sorry ArrayList,

Yea that worked, thanks very much



Can i just get it straight in my head,
In reality if i write int i=lines2.size();, and print i it is 6 (six elements),
but since the first element is located at 0, you write int i=lines2.size()-1 to start at element 5 which is last in ArrayList and i >= 0 so it will iterate down to 0 opposed to stopping at 1 if i write i > 0, Im i correct there?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Yes, perfect.
Mark Hughes
Ranch Hand

Joined: Jul 14, 2006
Posts: 146
Great Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Print attributes of ListArray in reverse