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.
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.
Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.
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.
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] .
No. Of course you can create a static method User.toString( User[] ), but it won't be called implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With