Java overloading toString() method when array of class is given [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-11 11:24:49

问题


This is how you overload the toString() method:

public class Person extends Object {
    @Override
    public final String toString() {
        Gson gson = new GsonBuilder().serializeNulls().create();
        return (gson.toJson(this));
    }
}

In this example I get a JSON string when calling the toString() method of Person instead of the default string representation of an Object.

But what if I have an array of Person like:

Person[] persons = new Person[3];
System.out.println(persons.toString());

What do I have to do or which method(s) do I have to override in that case?


回答1:


You cannot override default array's toString. If you want to convert an array of objects into the string, use Arrays.toString().




回答2:


You can't override the "array" version as their is no array version. What really happens is that the Array has a toString method which will be called.

If you had used a Java Collection as opposed to an Array, it would print out your Person#toString method 3 times as the Collection#toString iterates over each object in the collection.




回答3:


You cannot override method toString on array but you can use Arrays.toString(Object[]) to print array.




回答4:


First of all, you don't need to extend Object, it is there by default.

To print the array content you can use:

Person[] persons = new Person[3];
System.out.println(Arrays.toString(persons));


来源:https://stackoverflow.com/questions/16970488/java-overloading-tostring-method-when-array-of-class-is-given

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!