• Post Reply Bookmark Topic Watch Topic
  • New Topic

Fun with Arrays! How do I print out the index number alongside the elements in an array?  RSS feed

 
Mark Richardson
Ranch Hand
Posts: 108
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote this code (all by myself!) and it is printing out the elements found in the array, but I also want it to tell me that element 0 is Banana, element 1 is Apple, and so on...
How do I do this? Also, If it's possible, please feel free to tell me how to do more fun (but simple) things with arrays. Thank you!

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark,
Great question! There's two types of for loops. The one you used is an "enhanced for". It's less typing, but doesn't have the loop index available. This code is equivalent to yours but uses a traditional for loop. Now the index is available so you should be able to try printing it out.

}
 
s ravi chandran
Ranch Hand
Posts: 579
6
Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using a traditional for loop should work right?
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You said, “Fun with Arrays,“ but you don't have an array there. The method of using a plain for loop will work nicely with an ArrayList. In fact if you look here, you will find that plain for loop will run faster, but you won't notice the difference for a small List. If you use a LinkedList, however, which doesn't implement random access, the for‑each loop (=enhanced for loop) will be faster, and if you try that with a 10000000‑element linked list you will be surprised how slowly a plain for loop runs.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you wanted to stick with your enhanced loop, you could just declare a variable counter and increment it each time through.  As Campbel said, you don't realy have an array, but an ArrayList.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!