Creating toString method in custom ArrayList Java

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, ]

>Solution :

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() + "]";
    }
}

Leave a Reply