我如何可以覆盖在Java中一个ArrayList的toString方法? [英] How can I override the toString method of an ArrayList in Java?
问题描述
我想有自己的执行toString()方法的在Java的ArrayList。但是,我不能得到,即使我说我的toString()像这样包含的ArrayList类能够正常工作。
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;
}
当我打电话给我的ArrayList这样的 list.toString()
,我还是得到默认的重新presentation。我缺少的东西吗?
When I call my ArrayList like this list.toString()
, I still get the default representation. Am I missing something?
推荐答案
您应该做这样的事情。
public static String listToString(List<?> list) {
String result = "+";
for (int i = 0; i < list.size(); i++) {
result += " " + list.get(i);
}
return result;
}
和传递名单 listToString的参数()
。您的可以的技术上延长的ArrayList
(无论是与一个匿名类或具体的)和实施的toString
自己,但似乎没有必要在这里。
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.
这篇关于我如何可以覆盖在Java中一个ArrayList的toString方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!