Let's assume that I have a datastructure
with n
elements (0, 1, ... , n-1)
.
And assume these elements have some property I want to print (assume an int
). And I want to print the datastructure
on one line, with a delimiter (comma
, space
). So, the result would be something like this
13, 14, 15, 16, 17
What is the best way to add the comma and space (in Java)?
These are approaches I've taken:
If the
datastructure
isIterable
, iterate from0 to n-2
and append the delimiter to each of those, then print the last element.Loop through all elements and append everything to empty
String
(orStringbuilder
), then at the very end remove the last deliminator (hardcoded
).
I feel like there's something better.
Edit: The question is unique. The 'possible duplicate' involves only printing, not messing with delimiters.
Edit2: Attempts as requested
// 1st approach
public void printStuff(ArrayList<Integer> input) {
for (int i=0; i<input.size()-1; i++) {
System.out.print(input.get(i) + ", ");
}
System.out.println(input.get(input.size()-1);
}
Another attempt
// 2nd approach
public void printStuff(ArrayList<Integer> input) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<input.size(); i++) {
sb.append(input.get(i)+", ");
}
sb.substring(0, input.size()-2);
System.out.println(sb.toString());
}