Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 331
Popokoko Avatar asked Apr 24 '12 09:04

Popokoko


People also ask

Can we override toString method in Java?

We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.

Does ArrayList override toString?

Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.

Can toString be override?

Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

Can you use toString on an array?

The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object. prototype. toString is used instead, returning [object Array] .


1 Answers

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

like image 159
Theodore Norvell Avatar answered Sep 24 '22 14:09

Theodore Norvell