File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Print attributes of ListArray in reverse

 
Mark Hughes
Ranch Hand
Posts: 146
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Mark Hughes
Ranch Hand
Posts: 146
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, perfect.
 
Mark Hughes
Ranch Hand
Posts: 146
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great Thanks
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic