且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Java 中覆盖 ArrayList 的 toString 方法?

更新时间:2022-12-31 12:10:50

你应该做类似的事情

public static String listToString(List> list) {字符串结果 = "+";for (int i = 0; i < list.size(); i++) {结果 += " " + list.get(i);}返回结果;}

并将列表作为 listToString() 的参数传入.您可以在技术上扩展ArrayList(使用匿名类或具体类)并自己实现toString,但这在这里似乎没有必要.>

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?

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.