Java overloading toString() method when array of c

2019-07-27 07:38发布

问题:

This question already has an answer here:

  • How to convert an int array to String with toString method in Java [duplicate] 8 answers

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));