How can I override the toString method of an ArrayList in Java?

arraylist, java, overriding, tostring

Solution

You should do something like

public static String listToString(List<?> list) {
    String result = "+";
    for (int i = 0; i < list.size(); i++) {
        result += " " + list.get(i);
    }
    return result;
}

and pass the list in as an argument of `listToString()`. You can technically extend `ArrayList` (either with an anonymous class or a concrete one) and implement `toString` yourself, but that seems unnecessary here.

Problem

I would like to have my own implementation of the toString() method for an ArrayList in Java. However, I can't get it working even though I added my toString() like this to the class that contains the ArrayList. ``` @Override public String toString() { String result = "+"; for (int i = 0; i < list.size(); i++) { result += " " + list.get(i); } return result; } ``` When I call my ArrayList like this `list.toString()`, I still get the default representation. Am I missing something?

Original source

Related problems