Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading