*
The moose likes Beginning Java and the fly likes Having some trouble with this code. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Having some trouble with this code." Watch "Having some trouble with this code." New topic
Author

Having some trouble with this code.

Ben Jass
Ranch Hand

Joined: Sep 25, 2010
Posts: 76
Hey guys, I've been reading the Java Head First 2nd Edition book lately, and I've come across this code that I'm having a hard time to read.



I'm just began learning ArrayLists and I'm having trouble understanding how the printAL method works. One last question that I have is how do the "add" methods work?
For example:

a.add(0, "zero");

Does this code mean that I'm adding an object to the ArrayList with a string value of "zero"?
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

The printAl (shouldn't that be printAll) method uses an enhanced for-loop to print all the elements in the ArrayList. About your question about the add method. Just look at the documentation.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

for (String element : a1)

...means...

for each String (which we'll call "element") in a1.

So this will iterate through all Strings in a1. On the first iteration, "element" will reference the first String; on the second iteration, "element" will reference the second String; etc.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
 
subject: Having some trouble with this code.
 
Similar Threads
Can the index number be specified in the ArrayList add method
error with latest jdk
The Programme is not Compiling
ArrayList Question
ArrayListMagnet- problem compiling