Hi I'm writing code to print all elements from an ArrayList separated by comma, the folllowing is the method I wrote. It works. But i'm wondering if it can be simplified? And is there a more elegant way to print all elements from an ArrayList separated by some delimiter? (e.g. a method that prints an ArrayList of Strings get "Tom, Sherlock, Jack")
Thanks everyone!
public String printMyArrayList() {
if(mylist.size() == 0)return "";
else if(mylist.size() == 1)return mylist.get(0).toString();
else {
String returnStr = "";
for (int i = 0; i < mylist.size() ; i++) {
if(i == 0)returnStr = mylist.get(i).toString();
else {
returnStr = returnStr + ", " + mylist.get(i).toString();
}
}
return returnStr;
}
}
No comments:
Post a Comment