[JAVA] please tell me this for loop

  • Java
  • Thread starter uperkurk
  • Start date
  • #1
162
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.
 

Answers and Replies

  • #3
gabbagabbahey
Homework Helper
Gold Member
5,002
6
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:
  • #4
162
0
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!
 
  • #5
12,239
5,951
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.
 

Related Threads on [JAVA] please tell me this for loop

Replies
2
Views
863
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
4
Views
2K
Replies
19
Views
2K
Replies
7
Views
3K
  • Last Post
Replies
2
Views
5K
Replies
8
Views
2K
Replies
6
Views
2K
Replies
11
Views
2K
Replies
5
Views
1K
Top