This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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

Joined: Aug 31, 2004
Posts: 11343

for (String element : a1)


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
It is sorta covered in the JavaRanch Style Guide.
subject: Having some trouble with this code.
jQuery in Action, 3rd edition