I'm trying to loop through an ArrayList of Objects. For each Object, I want to call its toString() method and then join them with commas separating them.
I have some test code, but it's not performing like I would expect. The output I get for the following code is: Adam, Bob, Catherine, Dylan,
When what I want is Adam, Bob, Catherine, Dylan
(the last name shouldn't have a comma succeeding it.)
public static void main2 (){
//ArrayList of Strings rather than Objects for simplicity
ArrayList<String> test = new ArrayList<String>(Arrays.asList("Adam", "Bob", "Catherine", "Dylan"));
String output = new String();
for (String str : test) {
output += str.toString();
output += test.iterator().hasNext() ? ", " : "";
}
System.out.println(output);
}
Best Answer
,
only when the iterator has a next elementExample:
Output:
In the question, for the line
test.iterator()
returns an Iterator that points to the first elementhasNext()
will always be trueNote: It's good to use StringBuilder for things like these. :)