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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18129505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:35:23  来源:igfitidea点击:

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

javaarraylistoverridingtostring

提问by user2426316

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.

我想在 Java 中为 ArrayList 实现我自己的 toString() 方法。但是,即使我像这样将 toString() 添加到包含 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?

当我像这样调用我的 ArrayList 时list.toString(),我仍然得到默认表示。我错过了什么吗?

采纳答案by arshajii

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 cantechnically extend ArrayList(either with an anonymous class or a concrete one) and implement toStringyourself, but that seems unnecessary here.

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

回答by Luiggi Mendoza

You can't override the toStringmethod of ArrayList1. Instead, you can use a utility class that converts an ArrayListto a Stringthe way you want/need. Another alternative would be using Arrays.deepToString(yourList.toArray()).

您不能覆盖1toString方法。相反,你可以使用一个实用工具类,一种转换到你想要的方式/需求。另一种选择是使用.ArrayListArrayListStringArrays.deepToString(yourList.toArray())

Using Java 8, this can be done very easily:

使用 Java 8,这可以很容易地完成:

//List<String> list
System.out.println(String.join(",", list));

Or if you have a List<Whatever>:

或者,如果您有List<Whatever>

System.out.println(
    list.stream()
        .map(Whatever::getFieldX())
        .collect(Collectors.joining(", "))
);

I'm still against extending ArrayListor similar, is technically possible but I don't see it as a good option.

我仍然反对扩展ArrayList或类似,在技术上是可行的,但我认为它不是一个好的选择。



1you could extend ArrayListand override the toStringbut generally that's not a great idea. Further info:

1您可以扩展ArrayList和覆盖 ,toString但通常这不是一个好主意。更多信息:

回答by sashok724

ArrayList<String> list = new ArrayList<String>()
{
    private static final long serialVersionUID = 1L;

    @Override public String toString()
    {
        return super.toString();
    }
};

回答by Dennis Kriechel

You need to write a class extending from ArrayList:

您需要编写一个从 ArrayList 扩展的类:

import java.util.ArrayList;

public class MyArrayList extends ArrayList {
    private static final long serialVersionUID = 1L;

    @Override
    public String toString() {
        String result = "+";
        for (int i = 0; i < this.size(); i++) {
            result += " " + this.get(i);
        }
        return result;
    }
}

回答by Tom Ritch

To override toString() for ArrayList Integer array:

要覆盖 ArrayList 整数数组的 toString():

class MyArrayList extends ArrayList<Integer> {
    private static final long serialVersionUID = 1L;
    @Override public String toString(  ) {
        String output = "";
        for ( int i = 0 ; i < this.size(); i++ )
            output = Integer.toString( this.get( i ) );
        return output;
        }
    }

ArrayList<Integer> list = 
    new ArrayList<>(Arrays.asList( 5, 4, 2, 9, 1, 7 ) );
System.out.print( "list = " + list );

will generate: list = [5, 4, 2, 9, 1, 7]

将生成:list = [5, 4, 2, 9, 1, 7]

回答by Xiaogang

You can override the toString method in a new created class but you should make sure the created class extends ArrayList. Then, you can override toString method. This is based on IS relationship. The new created class is a type of ArrayList.

您可以在新创建的类中覆盖 toString 方法,但应确保创建的类扩展了 ArrayList。然后,您可以覆盖 toString 方法。这是基于IS关系。新创建的类是一种 ArrayList。

You can also create an ArrayList, which is based on the HAS relationship. In this case, you have to write another method to return String instead of override toString method.

您还可以创建一个 ArrayList,它基于 HAS 关系。在这种情况下,您必须编写另一个方法来返回 String 而不是覆盖 toString 方法。