I'm creating my own ArrayList
and stuck in the toString()
method, can you help me get rid of the comma after printing the last item?
toString()
method:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(store == null) {
return "[]";
} else {
for (int i = 0; i < size; i ) {
sb.append(store[i].toString() ", ");
}
return "[" sb.toString() "]";
}
}
Main
method:
public static void main(String[] args) {
MyArrayList<String> fruits = new MyArrayList<>();
System.out.println("My array list with fruits :)");
fruits.add("Bananas");
fruits.add("Apples");
fruits.add("Pineapple");
fruits.add("Peaches");
fruits.add("Pears");
fruits.add("Plum");
System.out.println("The list of fruits : " fruits);
fruits.clear();
System.out.println("All fruits have been eaten =) " fruits);
Output:
[Bananas, Apples, Pineapple, Peaches, Pears, Plum, ]
CodePudding user response:
Concat the comma at the start of the String and start the loop at index 1
if(store.length > 0) {
sb.append(store[0].toString());
}
for (int i = 1; i < store.length; i ) {
sb.append(", " store[i].toString());
}
CodePudding user response:
Just add an if condition to only add the comma if the index i
is not equals to the last index accepted by the for
loop
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if(store == null) {
return "[]";
} else {
for (int i = 0; i < size; i ) {
sb.append(store[i].toString());
if(i != size - 1) sb.append(",");
}
return "[" sb.toString() "]";
}
}