如何在 Java 中覆盖 ArrayList 的 toString 方法? [英] How can I override the toString method of an ArrayList in Java?
问题描述
我想在 Java 中为 ArrayList 实现我自己的 toString() 方法.但是,即使我像这样将 toString() 添加到包含 ArrayList 的类中,我也无法让它工作.
@Override公共字符串 toString() {字符串结果 = "+";for (int i = 0; i < list.size(); i++) {结果 += " " + list.get(i);}返回结果;}
当我像这样调用我的 ArrayList list.toString()
时,我仍然得到默认表示.我错过了什么吗?
你应该做类似的事情
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.
这篇关于如何在 Java 中覆盖 ArrayList 的 toString 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!