getClass().getName() + '@' + Integer.toHexString(hashCode())
Works as expected. Would it work for any class, as long as toString() isn't overridden?
Yes, seems to:
What about an array?
In this case, we get
The hashcode of the array doesn't agree.
I could understand that if there were some intervening class in the array's inheritance tree, in which toString() were overridden, but there isn't. The showTree() method shows that Object is directly descendant from Object. Plus, the class of Object, ie [Ljava.lang.Object; doesn't look like something I can look up in the api to see if it overrides toString().
How come toString() doesn't work as specified when invoked on an array?
is really the same as:
See if you can explain the results of:
Maybe replace new Object() with string literals to see what's happening.
Sresh Rangi wrote:In your example, toString() isn't being called on the array, it's being called on the first element within the array. Because printf takes vararg parameters, the last parameter is interpreted as an array containing the remaining parameters.
Well spotted Sresh . I could see it was printing the hashCode of an Object rather than the Object array, but i couldn't think why.
Richard, you can stop the Object array from being treated as var-args by adding a cast. Try
and see that the object class is now [Ljava.lang.Object; (an array of Objects) rather than java.lang.Object.
All clear now!