1

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?

arminb
  • 2,036
  • 3
  • 24
  • 43
  • 2
    It is not possible, but you can use Arrays.toString(Object[] a); which will call the toString() method on each object in the array. – michal Jun 06 '13 at 19:26
  • Why downvoting and requesting to close this question? I mean yes, there is another similar one but I could not find it because there are many ways to ask this question. Thanks for your help, I will use `Arrays.toString(Object[] a)`. – arminb Jun 06 '13 at 19:36

4 Answers4

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.

greedybuddha
  • 7,488
  • 3
  • 36
  • 50
1

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

tcb
  • 2,745
  • 21
  • 20
1

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

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
1

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));
Ederson
  • 133
  • 4