[JAVA] please tell me this for loop

  • Context: Java 
  • Thread starter Thread starter uperkurk
  • Start date Start date
  • Tags Tags
    Java Loop
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 2K views
uperkurk
Messages
167
Reaction score
0
Hey guys, I have an
Code:
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:
[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:
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.

Thanks.
 
Physics news on Phys.org
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:
ArrayList<String> al = new ArrayList<String>();
al.add("cat");
al.add("dog");
al.add("mouse");

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:
gabbagabbahey said:
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:
ArrayList<String> al = new ArrayList<String>();
al.add("cat");
al.add("dog");
al.add("mouse");

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.


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!
 
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.