Is it possible in Java to override 'toString' for an Objects array?

Is it possible in Java to override a toString for an Objects array?

For example, let's say I created a simple class, User (it doesn't really matter which class is it since this is a general question). Is it possible that, once the client creates a User[] array and the client uses System.out.print(array), it won't print the array's address but instead a customized toString()?

PS: of course I can't just override toString() in my class since it's related to single instances.


No. Of course you can create a static method User.toString( User[] ), but it won't be called implicitly.


You can use Arrays.toString(Object[] a); which will call the toString() method on each object in the array.

Edit (from comment):

I understand what it is you're trying to achieve, but Java doesn't support that at this time.

In Java, arrays are objects that are dynamically created and may be assigned to variables of type Object. All methods of class Object may be invoked on an array. See JLS Ch10

When you invoke toString() on an object it returns a string that "textually represents" the object. Because an array is an instance of Object that is why you only get the name of the class, the @ and a hex value. See Object#toString

The Arrays.toString() method returns the equivalent of the array as a list, which is iterated over and toString() called on each object in the list.

So while you won't be able to do System.out.println(userList); you can do System.out.println(Arrays.toString(userList); which will essentially achieve the same thing.


You can create a separate class containing the array, and override toString().

I think the simplest solution is to extend the ArrayList class, and just override toString() (for example, UserArrayList).