Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[JAVA] please tell me this for loop

  1. Oct 30, 2012 #1
    Hey guys, I have an
    Code (Text):
    ArrayList<String> al = ArrayList<String>();
    and I have a textbox, the textbox allows a user to enter a word and that word will be added into the ArrayList.

    When I print the list out it looks like this

    Code (Text):
    [Cat, Dog, Mouse]
    can you please write out the for loop that I need in order to change the ArrayList into a string? I want the output to look like this

    Code (Text):
    Cat Dog Mouse
    Please don't say go read this or read that, I've googled for loops but I can't find one that will do what I want.

  2. jcsd
  3. Oct 30, 2012 #2


    Staff: Mentor

  4. Oct 30, 2012 #3


    User Avatar
    Homework Helper
    Gold Member

    The collections-based for loop does almost the same thing, just behind the scenes (it uses and iterator in its implementation), and is a little easier to code:

    Code (Text):

    ArrayList<String> al = new ArrayList<String>();

    for(String str : al) {
        System.out.println(str + " ");
    For read-only access to your ArrayList, this is the way to go. You will run into problems if you try to remove objects from your ArrayList in such a loop, however (you will get a ConcurrentModificationException), whereas the while loop in jedishrfu's example will have no such problems.
    Last edited: Oct 30, 2012
  5. Oct 30, 2012 #4
    Exactly what I was looking for thank you so much! I had the exact same thing but I was using

    for(str : al) instead of for(string str : al)

    Cheers bro!
  6. Oct 30, 2012 #5


    Staff: Mentor

    With respect to the collections based for loop just be aware that it is in java 5 and beyond. Sometimes programmers are maintaining java 1.4 code or earlier and collections based for loops aren't supported.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook